How to join to the same table multiple times?
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 ;
You can use alias name for tables involved in query.
select b.name object, c.name parent_1, d.name parent_2
from hierarchy_table a, name_table b, name_table c, name_table d
where a.object_id = b.name_id
and a.parent_id_1 = c.name_id
and a.parent_id_2 = d.name_id