2013-10-20 85 views
0

我有一個數據庫來表示零售物品。有些項目有多個掃描碼,但本質上是相同的項目,即。他們的名字,成本和零售總是一樣的。爲了模擬此,the database has the following structureSQL JOIN獲取庫存物品和替代物品的清單

Inventory_Table 

INV_PK | INV_ScanCode | INV_Name | INV_Cost | INV_Retail 
    1 | 00| Muffins | 0.15  | 0.30  
    2 | 000987654321 | Cookie | 0.25  | 0.50  
    3 | 00| Cake | 0.45  | 0.90  


Alternates_Table 

ALT_PK | INV_FK | ALT_ScanCode 
    1 | 2 | 000999888777 
    2 | 2 | 000666555444 
    3 | 2 | 000333222111 

現在說我要在數據庫中的所有掃描代碼列表,我將如何連接表得到以下的輸出:

ScanCode  | Name | Cost | Retail 
00| Muffins | 0.15 | 0.30 
000987654321 | Cookie | 0.25 | 0.50 
000999888777 | Cookie | 0.25 | 0.50 
000666555444 | Cookie | 0.25 | 0.50 
000333222111 | Cookie | 0.25 | 0.50 
00| Cake | 0.45 | 0.90 

SQL Fiddle

回答

1

您正在尋找˚F或union

SELECT it.INV_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail 
FROM Inventory_Table AS it 
UNION ALL 
SELECT at.ALT_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail 
FROM Inventory_Table AS it 
    INNER JOIN Alternate_Table AS at 
    ON at.INV_FK = INV_PK 

UNION ALL是更快的選擇,當你知道行不會兩組結果的(所以DB不需要重複檢查)之間的重複。

1
SELECT it.INV_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail 
FROM Inventory_Table AS it 

union all 

SELECT at.ALT_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail 
FROM Alternate_Table AS at 
inner join Inventory_Table AS it on at.INV_FK = it.INV_PK 

SQL Fiddle

0

正如我所瞭解的查詢,你需要從庫存表中獲取所有內容。然後您需要使用inventory_tablealternates_table來選擇所有備選項。這建議整個查詢爲union all

select scancode, name, cost, retail 
from inventory_table i 
union all 
select a.scancode, i.name, i.cost, i.retail 
from inventory_table i join 
    alternates_table a 
    on a.inv_fk = i.inv_pk