2012-11-20 205 views
3

我有這種形式的兩個表:兩個左外連接

庫存:

Units InDate OutDate 

1000  11/4 12/4 

2000  13/4 14/4 

價格:

Date Price 
11/4 5 
12/4 4 
13/4 6 
14/4 7 

我想建立如下表:

Units InDate OutDate InPrice OutPrice 

1000  11/4 12/4  5  4 

2000  13/4 14/4  6  7 

我以爲我應該使用類似於:

Select * 
FROM Inventory 
LEFT OUTER JOIN Prices ON Inventory.InDate = Prices.Date 
LEFT OUTER JOIN Prices ON Inventory.OutDate = Prices.Date 

但是第二個OUTER JOIN似乎把事情弄糟了。

我該如何達到這個結果?

回答

4
Select 
    Units, 
    InDate, 
    OutDate, 
    P1.Price as InPrice, 
    P2.Price as OutPrice 
FROM Inventory 
LEFT OUTER JOIN Prices as P1 ON Inventory.InDate = P1.Date 
LEFT OUTER JOIN Prices as P2 ON Inventory.OutDate = P2.Date 
3

試試這個。

SELECT Inventory.Units, Inventory.InDate, Inventory.OutDate, InPrices.Price AS InPrice, OutPrices.Price AS OutPrice 
FROM Inventory 
LEFT OUTER JOIN Prices AS InPrices ON Inventory.InDate = InPrices.Date 
LEFT OUTER JOIN Prices AS OutPrices ON Inventory.OutDate = OutPrices.Date 
2

您當前的查詢非常接近正確。如果你在prices表上放置了不同的別名,那麼它會起作用。既然你要加入同一個表prices兩次,你需要使用一個不同的別名來區分他們:

select i.units, 
    i.indate, 
    i.outdate, 
    inPrice.price, 
    outPrice.price 
from inventory i 
left join prices inPrice -- first join with alias 
    on i.indate = inPrice.date 
left join prices outPrice -- second join with alias 
    on i.outdate = outPrice.date 

SQL Fiddle with Demo