-1

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?

GMB
  • 216,147
  • 25
  • 84
  • 135

2 Answers2

0

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.

GMB
  • 216,147
  • 25
  • 84
  • 135
0

You can use joins:

select i.*, coalesce(h1.grand_parent_name, h2.parent_name, h3.child_name) as hierarchy
from items i left join
     hierarchy h1
     on h1.grand_parent_id = i.item_id left join
     hierarchy h2
     on h2.parent_id = i.item_id left join
     hierarchy h3
     on h3.child_id = i.item_id;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786