代码笔记 | 📅 2021-07-06 | mysql sql
对单表内,字段数据进行统计
使用 count
方法
SELECT
count( `status` = 1 OR NULL ) AS queuing,
count( `status` = 2 OR `status` = 3 OR NULL ) AS running,
count( `status` = 5 OR NULL ) AS finished
FROM
some_table
WHERE
is_delete = 0;
执行结果如下:
+---------+---------+----------+
| queuing | running | finished |
+---------+---------+----------+
| 387 | 79 | 64 |
+---------+---------+----------+
COUNT() 函数返回匹配指定条件的行数。
COUNT()
函数的特性是:统计时不计入NULL数据。因此可以构造 SQL 如下:
SELECT
`status` = 6 OR NULL
FROM
some_table
WHERE
is_delete = 0;
此时,结果集中,status
字段为 6 的将返回 1,否则返回 NULL
+--------------------+
| `status`=6 or null |
+--------------------+
| 1 |
| 1 |
| NULL |
+--------------------+
应用 COUNT()
函数,即可得设定条件下的统计结果:
SELECT
count(`status` = 6 OR NULL)
FROM
some_table
WHERE
is_delete = 0;
返回
+---------------------------+
| count(`status`=6 or null) |
+---------------------------+
| 2 |
+---------------------------+