I have two tables hierarchy
and item
which I'd like to join:
hierarchy
|------------------|------------------|-------------|--------------|------------|--------------|
| grandparent_id | grandparent_name | parent_id | parent_name | child_id | child_name |
|------------------|------------------|-------------|--------------|------------|--------------|
| 100 | Make | 101 | Model | 102 | CPU |
|------------------|------------------|-------------|--------------|------------|--------------|
item
|-----------|-------------|
| item_id | item_name |
|-----------|-------------|
| 100 | Dell |
| 101 | XPS |
| 102 | i5-9300H |
|-----------|-------------|
desired output:
|-----------|-------------|-------------|
| item_id | item_name | hierarchy |
|-----------|-------------|-------------|
| 100 | Dell | Make |
| 101 | XPS | Model |
| 102 | i5-9300H | CPU |
|-----------|-------------|-------------|
What would be the most efficient way to perform this query?
You could unpivot the columns of the hierarchy, then join:
select i.item_id, i.item_name, h.model
from item i
inner join (
select grand_parent_id item_id, grand_parent_name model from hierarchy
union all select parent_id, parent_name from hierarchy
union all select child_id, child_name from hierarchy
) h on h.item_id = i.item_id
If there may be missing items in the hierarchy, then you can use left join
instead of inner join
.