2つのテーブルが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 |
|-----------|-------------|
望ましい出力:
|-----------|-------------|-------------|
| item_id | item_name | hierarchy |
|-----------|-------------|-------------|
| 100 | Dell | Make |
| 101 | XPS | Model |
| 102 | i5-9300H | CPU |
|-----------|-------------|-------------|
このクエリを実行する最も効率的な方法は何ですか?
階層の列のピボットを解除してから結合できます。
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
階層に不足しているアイテムがある場合は、のleft join
代わりに使用できますinner join
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加