简体   繁体   中英

How to join a table with Grandparent-Parent-Child columns in SQL?

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 .

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM