我有这些表
Item
+-------+--------+
| ID | Name |
+-------+--------+
| 1 | itemA |
+-------+--------+
Sales
+-------+--------+-------------+-----+
| ID | ItemID | WarehouseID | ... |
+-------+--------+-------------+-----+
| ABC | 1 | null | ... |
+-------+--------+-------------+-----+
ItemID = FK of Item(ID)
WarehouseID = FK of Warehouse(ID)
Warehouse
+--------+----------+------+-------+
| ID | ItemID | Qty | Price |
+--------+----------+------+-------+
| 1 | 1 | 10 | 5.00 |
+--------+----------+------+-------+
ItemID = FK of Item(ID)
**Expected Results:**
+--------+----------+----------------+-------------+------+-------+
| ItemID | ItemName | SalesID | WarehouseID | Qty | Price |
+--------+----------+----------------+-------------+------+-------+
| 1 | itemA | ABC | null | null | null |
+--------+----------+----------------+-------------+------+-------+
它为null因为" WarehouseID"在销售中为空。
我怎么能这样做..我试过但是由于空值,结果没有返回任何行。
答案 0 :(得分:3)
您可以INNER JOIN
使用LEFT OUTER JOIN
+ WarehouseId
:
SELECT item.ID as ItemID, item.Name as ItemName,
sales.Id as SalesID,
sales.WarehouseID,
wh.Qty, wh.Price
FROM Item
INNER JOIN Sales
ON item.ID = sales.ItemID
LEFT OUTER JOIN Warehouse wh
ON sales.WarehouseID = wh.ID
答案 1 :(得分:2)
select i.ID as ItemID,
i.Name as ItemName,
s.ID as SalesID,
w.ID as WarehouseID,
w.Qty as Qty,
w.Price as Price
from (Item i join Sales s
on i.Id = s.ItemID) left join
WareHouse w on w.ItemId = i.ID and w.SalesID = s.ID
内部联接在Sales
和Item
以及外部联接(查询中的左)到{{ 1}}?
答案 2 :(得分:0)
试试这个
SELECT COALESCE(i.ItemId,NULL),COALESCE(i.ItemName,NULL)
s.SalesID,COALESCE(w.WarehouseID,NULl),
COALESCE(w.Qty,NULL),COALESCE(w.Price,NULL)
FROM Sales s
LEFT JOIM Item i On s.ItemID = i.ItemID
LEFT JOIN Warehouse w ON s.WarehouseID =w.WarehouseID
答案 3 :(得分:-1)
我不知道什么是数据库,但请阅读outer join
。它在所有sql'引擎中都很常见