Mysql条件总和

时间:2015-08-04 11:02:15

标签: mysql sql

这是我的sql

    SELECT A.item_code,A.description,A.uom, A.open_stock, B.recd_total, C.issue_qty 
FROM    chem_master as A 
        LEFT JOIN ( 
                SELECT item_code,  SUM(recd_qty) as recd_total 
                FROM  chem_receipts 
                GROUP BY item_code) AS B 
            ON A.item_code=B.item_code 
        LEFT JOIN(
                SELECT item_code, sum(iss_qty) as issue_qty 
                FROM chem_issue 
                GROUP BY item_code) as C 
            ON A.item_code=C.item_code 
HAVING (open_stock+recd_total-issue_qty) IS NULL OR (open_stock+recd_total-issue_qty)=0

这里,表chem_receipts& chem_issue没有chem_master中的所有匹配记录。此外,可能有多个匹配记录。

我想显示库存为0的商品.chem_master中有300件商品。但是在chem_receipts中只有15条记录,因为我们只在这15项中购买了额外的产品。 chem_issue有100条记录。

现在,对于没有进行额外购买的项目的返回查询显示为NULL&同样是永远不会发出物品的情况。

我知道添加' 0'所有项目的记录在发行数量和收据表中将解决问题。但这不是一个更好的方法。

如何改进此查询?

2 个答案:

答案 0 :(得分:0)

我想你只想要COALESCE()

SELECT A.item_code, A.description, A.uom, A.open_stock,
       COALESCE(B.recd_total, 0) as recd_total,
       COALESCE(C.issue_qty, 0) as issue_qty
FROM . . .

答案 1 :(得分:0)

您会被数字0NULL之间的区别所震撼。你非常接近正确的答案。

如果我是你,有300件商品,我会从未经过滤的查询开始,显示每件商品的库存。

SELECT A.item_code,A.description,A.uom, 
       A.open_stock, 
       IFNULL(B.recd_total,0) recd_total, 
       IFNULL(C.issue_qty,0) issue_qty 
 FROM chem_master as A 
 LEFT JOIN ( 
            SELECT item_code,  SUM(recd_qty) as recd_total 
            FROM  chem_receipts 
            GROUP BY item_code) AS B 
        ON A.item_code=B.item_code 
 LEFT JOIN(
            SELECT item_code, sum(iss_qty) as issue_qty 
            FROM chem_issue 
            GROUP BY item_code) as C 
        ON A.item_code=C.item_code

请注意,IFNULL()操作会将LEFT JOIN未命中的NULL结果转换为数字0值。 (COALESCE()也适用于此。)

然后,将其用作进行过滤的主查询的子查询。

SELECT item_code, description, uom,
       open_stock, recd_total, issue_qty,
       open_stock+recd_total-issue_qty in_stock_qty
  FROM (
        SELECT A.item_code,A.description,A.uom, 
               A.open_stock, 
               IFNULL(B.recd_total,0) recd_total, 
               IFNULL(C.issue_qty,0) issue_qty 
         FROM chem_master as A 
         LEFT JOIN ( 
                    SELECT item_code,  SUM(recd_qty) as recd_total 
                      FROM  chem_receipts 
                  GROUP BY item_code) AS B 
               ON A.item_code=B.item_code 
         LEFT JOIN(
                    SELECT item_code, sum(iss_qty) as issue_qty 
                      FROM chem_issue 
                  GROUP BY item_code) as C 
                ON A.item_code=C.item_code 
) DETAIL
WHERE (open_stock+recd_total-issue_qty) = 0