MYSQL使用IF选择计数

时间:2016-09-29 08:14:38

标签: mysql select count

我想让所有用户拥有多个具有部门状态的订单

我的查询:

SELECT 
    users.id as "Id", 
    users.firstname as "Firstname", 
    users.lastname as "Lastname",
    COUNT(IF(orders.status = 0, 1, 0)) as "Status #0",
    COUNT(IF(orders.status = 1, 1, 0)) as "Status #1",
    COUNT(IF(orders.status = 2, 1, 0)) as "Status #2",
    COUNT(IF(orders.status = 3, 1, 0)) as "Status #3",
    COUNT(IF(orders.status = 4, 1, 0)) as "Status #4",
    COUNT(IF(orders.status = 5, 1, 0)) as "Status #5",
    COUNT(IF(orders.status = 6, 1, 0)) as "Status #6",
    COUNT(IF(orders.status = 7, 1, 0)) as "Status #7",
    COUNT(IF(orders.status = 8, 1, 0)) as "Status #8"
FROM 
    users 
    LEFT JOIN orders ON orders.idu = users.id 
WHERE 
    users.register_complete = 1 
GROUP BY 
    users.id 
ORDER BY 
    users.date_register DESC

结果: enter image description here

所有状态都是一样的......哪里有问题? 谢谢! :)

1 个答案:

答案 0 :(得分:1)

如果count(value)不是1

value将被计为null,请参阅documentation

  

<强> COUNT(表达式)

     

返回SELECT语句检索的行中expr的非NULL值的计数。结果是BIGINT值。

所以你计算了每一行,与你的IF条件无关。

count更改为sum,或将0更改为null以获得所需结果:

...
COUNT(IF(orders.status = 0, 1, null))
...