用于检索一列为空的数据的SQL命令

时间:2015-09-01 14:28:52

标签: sql

我有这些表

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"在销售中为空。

我怎么能这样做..我试过但是由于空值,结果没有返回任何行。

4 个答案:

答案 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

内部联接SalesItem以及外部联接(查询中的)到{{ 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'引擎中都很常见