1

MySQL 字段统计操作

 2 years ago
source link: https://blog.moonlightwatch.com/%E4%BB%A3%E7%A0%81%E7%AC%94%E8%AE%B0/2021/07/06/MySQL-%E5%AD%97%E6%AE%B5%E7%BB%9F%E8%AE%A1%E6%93%8D%E4%BD%9C.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

MySQL 字段统计操作

代码笔记 | 📅 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 |
+---------------------------+ 

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK