MySQL - 复杂的CASE / WHEN条件可能吗?

时间:2013-01-17 07:20:42

标签: mysql case conditional-statements ifnull

此问题与我之前的帖子有关:MySQL - Complicated SUMs inside Query

查询效果很好,总结了所需的总数。 我注意到它也忽略了任何带有NULL值的记录。

当前查询:

SELECT c.*,
        SUM(CASE WHEN billtype = 1 THEN total ELSE 0 END) totalpaid ,
        SUM(CASE WHEN billtype = 2 THEN total ELSE 0 END) totalowed ,
        SUM(total) AS totalbalance
FROM 
    tbl_customers c
    LEFT JOIN tbl_customers_bills  b
    ON c.customerid = = b.customerid
     and billtype in (1,2)
GROUP BY 
     c.customerid

它可以很好地返回 10 客户记录。 当我检查数据库时,我可以看到 11 客户记录,并且第11个在tbl_customers_bills表中没有相关记录。

即使tbl_customers_bills表中存在不存在的记录,我还是要返回所有11个。 (但当然是零)

我对这种情况有多复杂感到困惑。 这是我尝试过的:(无济于事)

SELECT c.*,

     (CASE WHEN (total IS NULL) THEN totalpaid = 0

       ELSE
        SUM(CASE WHEN billtype = 1 THEN total ELSE 0 END) totalpaid ,
        SUM(CASE WHEN billtype = 2 THEN total ELSE 0 END) totalowed ,
        SUM(total) AS totalbalance
      END)

FROM 
    tbl_customers c
    LEFT JOIN tbl_customers_bills  b
    ON c.customerid = = b.customerid
     and billtype in (1,2)
GROUP BY 
     c.customerid

2 个答案:

答案 0 :(得分:2)

我可能完全相信,但我相信你只是缺少COALESCE

SELECT c.*,
       COALESCE(SUM(CASE WHEN billtype = 1 THEN total ELSE 0 END), 0) totalpaid ,
       COALESCE(SUM(CASE WHEN billtype = 2 THEN total ELSE 0 END), 0 totalowed ,
       COALESCE(SUM(total), 0) AS totalbalance
FROM 
    tbl_customers c
    LEFT JOIN tbl_customers_bills  b
    ON c.customerid = = b.customerid
     and billtype in (1,2)
GROUP BY 
     c.customerid

来自MySQL Reference

  

COALESCE(值,...)

     

返回列表中的第一个非NULL值,如果没有则返回NULL   非NULL值。

     

的MySQL> SELECT COALESCE(NULL,1);            - > 1
  MySQL的> SELECT COALESCE(NULL,NULL,NULL);            - > NULL

答案 1 :(得分:1)

如何做ifnull

SELECT 
    c.*,
    SUM(CASE WHEN billtype = 1 THEN IFNULL(total,0) ELSE 0 END) totalpaid ,
    SUM(CASE WHEN billtype = 2 THEN IFNULL(total,0) ELSE 0 END) totalowed ,
    SUM(total) AS totalbalance
FROM 
    tbl_customers c
    LEFT JOIN tbl_customers_bills  b
    ON c.customerid = = b.customerid
     and billtype in (1,2)
GROUP BY 
     c.customerid