当使用sum(条件1的情况)和count(条件1的情况)时,MYSQL的结果不同

时间:2018-12-29 06:49:39

标签: mysql

我使用以下查询对行进行计数,不知道何时在查询中使用sum()返回正确的行,但是当我使用count返回false时。我已经完成了这项工作,但是我需要澄清一下自己的进一步发展

SELECT SUM(CASE 
         WHEN g.branchid=30  THEN 1
         ELSE 0
       END) AS count FROM `liverates` l LEFT JOIN branch b ON b.warehouseid=l.warehouseid LEFT JOIN `group` g ON l.warehouseid=g.warehouseid

SELECT COUNT(CASE 
         WHEN g.branchid=30  THEN 1
         ELSE 0
       END) AS count FROM `liverates` l LEFT JOIN branch b ON b.warehouseid=l.warehouseid LEFT JOIN `group` g ON l.warehouseid=g.warehouseid

SUM()以上返回215个正确结果,然后count()未返回实际结果,而是返回了表的总计数

2 个答案:

答案 0 :(得分:2)

>>> def fun_varargs(a = 5, *numbers, **dict): ... print("value of a is", a) ... for i in numbers: ... print("value of i is", i) ... for i, j in dict.items(): ... print("The value of i and j are:", i,j) ... >>> fun_varargs(fun_varargs.__defaults__[0],1,2,3,4,5,6,7,8,9,10,Jack=111,John=222,Tom=333) value of a is 5 value of i is 1 value of i is 2 value of i is 3 value of i is 4 value of i is 5 value of i is 6 value of i is 7 value of i is 8 value of i is 9 value of i is 10 The value of i and j are: Jack 111 The value of i and j are: John 222 The value of i and j are: Tom 333 会计算所有非空值,无论它们是什么。因此count()也算在内。

这将适用于0

count()

或仅保留COUNT(CASE WHEN g.branchid=30 THEN 1 ELSE NULL END) 部分

else

特别是在MySQL中,您可以像这样简化COUNT(CASE WHEN g.branchid=30 THEN 1 END) (因为条件的结果是sum()1

0

答案 1 :(得分:1)

COUNT()将计算遇到的行数,因此即使您的case将值操纵为1或0,它仍然是一行,因此将被计数。

>

如果您只想要g.branchid=30所在的行,则将其变成WHERE子句...

SELECT COUNT(*) AS count 
    FROM `liverates` l 
    LEFT JOIN branch b ON b.warehouseid=l.warehouseid 
    LEFT JOIN `group` g ON l.warehouseid=g.warehouseid
    WHERE g.branchid=30

这将忽略它不感兴趣的行,并可能使用索引。您也许还可以删除指向分支表的链接,因为在这种情况下看起来好像不相关...

SELECT COUNT(*) AS count 
    FROM `liverates` l 
    LEFT JOIN `group` g ON l.warehouseid=g.warehouseid
    WHERE g.branchid=30