如何修复MySQL查询不返回空值

时间:2019-10-02 06:59:50

标签: mysql

这是我的查询

const sortedEvents = events.filter(event =>
event.start.dateTime >= today
&& event.end.dateTime <= nextWeek.toISOString()
);

stock_report_sample

当执行上述查询时,如果所选表之一没有该特定日期的项目ID,则返回空值。我希望它显示所有可用项目(产品)的列表,即使该项目尚未出售或未收到,因此在那些情况下它应显示零(0)

2 个答案:

答案 0 :(得分:1)

也许您可以使用ISNULL来显示零(如果为NULL)

SELECT 
    p.pcode, 
    p.productName, 
    s.pcode, 
    ISNULL(MAX(s.in_stock),0) AS opening_stock, 
    ISNULL(SUM(s.soldQty),0) AS sold_qty, 
    ISNULL(MIN(s.remaining_qty),0) AS closing_stock, 
    s.date_created,
    g.pcode, 
    g.qty, 
    g.received_qty, 
    g.received_on 
FROM tbl_products p 
LEFT JOIN tbl_sold_items s ON p.pcode = s.pcode 
LEFT JOIN tbl_shop_gr_items g ON p.pcode = g.pcode 
WHERE(s.date_created = '2019-09-27') AND (g.received_on = '2019-09-27') 
GROUP BY p.pcode

答案 1 :(得分:0)

    SELECT 
p.pcode,
p.productName,
CASE
        WHEN gr_rows IS NULL AND sl_rows IS NULL THEN 0
        WHEN gr_rows > 0 AND sl_rows IS NULL THEN received_stock
        WHEN gr_rows > 0 AND sl_rows > 0 THEN opening_stock
        ELSE 0
    END AS op_stock,
    IFNULL(received_stock, 0),IFNULL(sold_stock, 0)
FROM tbl_products p
LEFT JOIN (
    SELECT COUNT(r.ID) AS gr_rows,r.pcode,r.received_on,SUM(r.received_qty) AS received_stock
    FROM tbl_shop_gr_items r
    WHERE r.received_on = '2019-10-03'
    GROUP BY r.pcode
)AS r ON p.pcode = r.pcode
LEFT JOIN (
    SELECT COUNT(s.ID) AS sl_rows,s.pcode,s.date_created,SUM(s.soldQty) AS sold_stock
    FROM tbl_sold_items s
    WHERE s.date_created = '2019-10-03'
    GROUP BY s.pcode
)AS s ON p.pcode = s.pcode
LEFT JOIN (
    SELECT t.ID,t.pcode,t.date_created,t.remaining_qty AS opening_stock
    FROM tbl_sold_items t
    WHERE t.date_created > '2019-10-03'
    GROUP BY t.pcode ORDER BY t.ID
)AS t ON p.pcode = t.pcode

上面的代码解决了我的问题