[英]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
和item
我想加入其中:
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
.如果层次结构中可能缺少项目,那么您可以使用left join
而不是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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.