作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想让所有拥有多个具有部门状态的订单的用户
我的查询:
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
所有状态都相同......问题出在哪里?谢谢! :)
最佳答案
如果 value
不是 null
,
count(value)
将计为 1
,请参见 documentation :
COUNT(expr)
Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement. The result is a BIGINT value.
因此,您计算了每一行,与 IF
条件无关。
将 count
更改为 sum
,或将 0
更改为 null
以获得所需的结果:
...
COUNT(IF(orders.status = 0, 1, null))
...
关于MYSQL 使用 IF 选择计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39764892/
我是一名优秀的程序员,十分优秀!