SQL Left Join以null结果返回0

时间:2016-03-31 08:21:21

标签: sql sql-server

我有这样的查询

SELECT 
  a.STOCK_ITEM_NO, a.STOCK_BEG_QTY, b.DOUT_QTY_ISSUE 
FROM
  INV_STOCK AS a 
  LEFT OUTER JOIN INV_DOUT AS b 
    ON a.STOCK_ITEM_NO = b.DOUT_ITEM_NO 
WHERE a.STOCK_ITEM_NO = 'ABC01' 
  AND b.CREATEDDATE > '01-MAR-2016' 
  AND b.CREATEDDATE < '01-APR-2016' 

时有null
select dout_qty_issue from inv_dout where b.CREATEDDATE > '01-MAR-2016' and b.CREATEDDATE < '01-APR-2016'

因为没有数据

所以查询的结果是空的,因为它无法加入(我认为) 但它能回来吗?

'ABC01' | 10  | 0

因为现在查询返回

null | null| null

3 个答案:

答案 0 :(得分:3)

SELECT a.STOCK_ITEM_NO
      ,a.STOCK_BEG_QTY
      ,ISNULL(b.DOUT_QTY_ISSUE,0) as DOUT_QTY_ISSUE
FROM INV_STOCK AS a
LEFT JOIN INV_DOUT AS b
    ON a.STOCK_ITEM_NO = b.DOUT_ITEM_NO
       AND b.CREATEDDATE > '01-MAR-2016'
       AND b.CREATEDDATE < '01-APR-2016'
WHERE a.STOCK_ITEM_NO = 'ABC01'

将where条件设置为Join,您可以显示所需内容。

答案 1 :(得分:1)

试试这个,将左连接表的过滤从WHERE移到ON子句。

SELECT a.STOCK_ITEM_NO, a.STOCK_BEG_QTY, ISNULL(b.DOUT_QTY_ISSUE,0) DOUT_QTY_ISSUE
FROM
  INV_STOCK AS a 
  LEFT OUTER JOIN INV_DOUT AS b 
    ON a.STOCK_ITEM_NO = b.DOUT_ITEM_NO 
     AND b.CREATEDDATE > '01-MAR-2016' 
     AND b.CREATEDDATE < '01-APR-2016' 
WHERE a.STOCK_ITEM_NO = 'ABC01' 

答案 2 :(得分:0)

将您的日期WHERE语句放在LEFT JOIN中。

SELECT a.STOCK_ITEM_NO,a.STOCK_BEG_QTY, b.DOUT_QTY_ISSUE
FROM INV_STOCK a 
LEFT OUTER JOIN INV_DOUT b ON a.STOCK_ITEM_NO = b.DOUT_ITEM_NO 
AND b.CREATEDDATE BETWEEN '01-MAR-2016' AND '01-APR-2016'
WHERE a.STOCK_ITEM_NO = 'ABC01'