两个左外连接

时间:2012-11-20 10:51:44

标签: sql

我有两种表格形式:

清单:

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

但是第二次外部加入似乎搞得一团糟。

如何达到此结果?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 :(得分: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