我想让所有用户拥有多个具有部门状态的订单
我的查询:
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
所有状态都是一样的......哪里有问题? 谢谢! :)
答案 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))
...