2012-11-20 174 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