snippetsqlModerate
How to join to the same table multiple times?
Viewed 0 times
samethejoinmultiplehowtimestable
Problem
I have two tables, "hierarchy_table" and "name_table".
The hierarchy table contains an object which has multiple parents and children. Each parent and child is referenced by id.
Each object id in the hierarchy_table has an entry in the name_table:
How do I join each id in the hierarchy_table to the name_table multiple times so that I can have a result where every name is populated?
Like this:
Note: the table names in the example are just for clarity / simplicity, the real names have proper names.
The hierarchy table contains an object which has multiple parents and children. Each parent and child is referenced by id.
| object_id | parent_id_1 | parent_id_2 | child_id_1 | child_id_2 |
-----------------------------------------------------------------------------
| 1234 | 9999 | 9567 | 5555 | 5556 |
-----------------------------------------------------------------------------Each object id in the hierarchy_table has an entry in the name_table:
| name_id | name |
--------------------------
| 1234 | ABCD |
--------------------------
| 9999 | ZYXW |
--------------------------
| ...How do I join each id in the hierarchy_table to the name_table multiple times so that I can have a result where every name is populated?
Like this:
| object | parent_1 | parent_2 | child_1 | child_2 |
-----------------------------------------------------------------------------
| ABCD | ZYXW | BBBB | CCCC | DDDD |
-----------------------------------------------------------------------------Note: the table names in the example are just for clarity / simplicity, the real names have proper names.
Solution
The
hierarchy_table has 5 columns that all reference the name_table, so you need 5 joins. It may be better to use LEFT joins instead of INNER, in case some of these columns are nullable and you still want the rows returned:SELECT
o.name AS object,
p1.name AS parent_1,
p2.name AS parent_2,
c1.name AS child_1,
c2.name AS child_2
FROM
hierarchy_table AS h
LEFT JOIN name_table AS o ON h.object_id = o.name_id
LEFT JOIN name_table AS p1 ON h.parent_id_1 = p1.name_id
LEFT JOIN name_table AS p2 ON h.parent_id_2 = p2.name_id
LEFT JOIN name_table AS c1 ON h.child_id_1 = c1.name_id
LEFT JOIN name_table AS c2 ON h.child_id_2 = c2.name_id ;Code Snippets
SELECT
o.name AS object,
p1.name AS parent_1,
p2.name AS parent_2,
c1.name AS child_1,
c2.name AS child_2
FROM
hierarchy_table AS h
LEFT JOIN name_table AS o ON h.object_id = o.name_id
LEFT JOIN name_table AS p1 ON h.parent_id_1 = p1.name_id
LEFT JOIN name_table AS p2 ON h.parent_id_2 = p2.name_id
LEFT JOIN name_table AS c1 ON h.child_id_1 = c1.name_id
LEFT JOIN name_table AS c2 ON h.child_id_2 = c2.name_id ;Context
StackExchange Database Administrators Q#145038, answer score: 18
Revisions (0)
No revisions yet.