2015-10-14 23 views
0

這是我的第一篇文章。對不起,如果多餘或不夠具體。SQL查詢加入2個部分的項目描述

我是SQL的新手,可能會把這想法變成一個思維模塊。

我有一個表「parent_item_id」和「child_item_id」但沒有說明。我想要做一個查詢來包含這兩個項目的描述。

我的出發點是:

SELECT B.P_ITEM as Parent, I.description as P_desc, B.C_ITEM, I.description as C_desc 
from boms B 
left join items I on B.P_ITEM = I.item_id 

據我所知,將把母公司描述爲家長和孩子都領域。

如何創建一個查詢,該查詢將爲我提供一行中父項和子項的描述?

感謝

回答

0

讓我們假設你的物料清單是這樣的非常簡單:

ID p_item c_item quantity 
1 1   500  1 
2 1   600  4 

項目表可能有

ID description 
1 Big Computer 
500 128GB SSD 
600 2GB Memory 

您的查詢將是這樣的:

select b.*, p.description, c.description 
from bom b 
inner join items p on p.id = b.p_item 
inner join items c on c.id = b.c_item 

結果:

| id | p_item | c_item | quantity | description | description | 
|----|--------|--------|----------|--------------|-------------| 
| 1 |  1 | 500 |  1 | Big Computer | 128G SSD | 
| 2 |  1 | 600 |  4 | Big Computer | 2GB Memory | 

例子:http://sqlfiddle.com/#!9/340e07/1

+0

謝謝你,這是簡單的解決方案和工作就像一個冠軍。我將不得不記住內部連接! – Sareed23