当前位置:网站首页>MySql统计函数COUNT详解
MySql统计函数COUNT详解
2022-07-29 05:20:00 【本本的香菜】
MySql统计函数COUNT详解
1. COUNT()函数概述
COUNT() 是一个聚合函数,返回指定匹配条件的行数。开发中常用来统计表中数据,全部数据,不为NULL数据,或者去重数据。
2. COUNT()参数说明
COUNT(1):统计不为NULL 的记录。
COUNT(*):统计所有的记录(包括NULL)。
COUNT(字段):统计该"字段"不为NULL 的记录。
1.如果这个字段是定义为not null的话,一行行地从记录里面读出这个字段,判断不能为null,按行累加。
2.如果这个字段定义允许为null的话,判断到有可能是null,还要把值取出来在判断一下,不是null才累加。
COUNT(DISTINCT 字段):统计该"字段"去重且不为NULL 的记录。
-- MySql统计函数count测试
-- 创建用户表,新增测试数据
CREATE TABLE `user` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID主键',
`name` varchar(64) DEFAULT NULL COMMENT '姓名',
`sex` varchar(8) DEFAULT NULL COMMENT '性别',
`age` int(4) DEFAULT NULL COMMENT '年龄',
`born` date DEFAULT NULL COMMENT '出生日期',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='用户表';
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (1, '%张三%', '男', 22, '2022-04-22');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (2, '李四', '女', 12, '2022-04-01');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (3, '王小二', '女', 12, '2022-04-28');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (4, '赵四', '男', 23, '2022-04-28');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (5, '', '女', 23, '2022-04-28');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (6, NULL, '女', 60, '2022-04-28');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (7, NULL, '女', 61, '2022-04-28');
select * from user;
-- 统计数据:7条数据,统计所有的记录(包括NULL)。
select count(*) from user;
-- 统计数据:7条数据,统计不为NULL 的记录。
select count(1) from user;
-- 统计数据:5条数据,COUNT(字段):统计该"字段"不为NULL 的记录,注意是null不是空''字符串
select count(name) from user;
-- 统计数据:5条数据,COUNT(DISTINCT 字段):统计该"字段"去重且不为NULL 的记录。
select count(distinct name) from user;
3. COUNT()判断存在
SQL不再使用count,而是改用LIMIT 1,让数据库查询时遇到一条就返回,不要再继续查找还有多少条了,业务代码中直接判断是否非空即可。
select 1 from emp LIMIT 1;效率是最高的,尤其是需要limit限制行数,很容易忽略。
-- SQL查找是否"存在"
-- 员工表,存在则进行删除
drop table if EXISTS emp;
create table emp(
id int unsigned primary key auto_increment,
empno mediumint unsigned not null default 0,
empname varchar(20) not null default "",
job varchar(9) not null default "",
mgr mediumint unsigned not null default 0,
hiredate datetime not null,
sal decimal(7,2) not null,
comn decimal(7,2) not null,
depno mediumint unsigned not null default 0
);
-- 新增cehsi数据
测试数据:https://blog.csdn.net/m0_37583655/article/details/124385347
-- cahxun
select * from emp ;
-- 时间:1.082s,数据:5000000
explain select count(*) from emp;
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE Select tables optimized away
-- 时间:1.129s,数据:5000000
explain select count(1) from emp;
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE Select tables optimized away
-- 时间:1.695s,数据:5000000
explain select 1 from emp;
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE emp idx_emp_depno 3 4981060 100.00 Using index
-- SQL不再使用count,而是改用LIMIT 1,让数据库查询时遇到一条就返回,不要再继续查找还有多少条了,业务代码中直接判断是否非空即可
-- 时间:0.001s,数据:5000000
explain select 1 from emp LIMIT 1;
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE emp idx_emp_depno 3 4981060 100.00 Using index
4. COUNT()阿里开发规范
1.【强制】不要使用 count(列名)或 count(常量)来替代 count(),count()是 SQL92 定义的标 准统计行数的语法,跟数据库无关,跟 NULL 和非 NULL 无关. 说明:count(*)会统计值为 NULL 的行,而 count(列名)不会统计此列为 NULL 值的行.
2.【强制】count(distinct col) 计算该列除 NULL 之外的不重复行数,注意 count(distinct col1, col2) 如果其中一列全为 NULL,那么即使另一列有不同的值,也返回为 0.

边栏推荐
- CMD window under Windows connects to MySQL and operates the table
- 我的理想工作,码农的绝对自由支配才是最重要的——未来创业的追求
- Breaking through the hardware bottleneck (I): the development of Intel Architecture and bottleneck mining
- Windows下cmd窗口连接mysql并操作表
- How to survive in the bear market of encryption market?
- 熊市慢慢,Bit.Store提供稳定Staking产品助你穿越牛熊
- Laravel swagger add access password
- 山寨币SHIB 在 ETH 鲸鱼的投资组合中拥有 5.486 亿美元的股份——交易者应提防……
- 『全闪实测』数据库加速解决方案
- Okaleido tiger logged into binance NFT on July 27, and has achieved good results in the first round
猜你喜欢

『全闪实测』数据库加速解决方案

Super simple integration of HMS ml kit to realize parent control

“山东大学移动互联网开发技术教学网站建设”项目实训日志三

华为2020校招笔试编程题 看这篇就够了(下)

Starfish OS: create a new paradigm of the meta universe with reality as the link

Go|Gin 快速使用Swagger

北京宝德&TaoCloud共建信创之路

Okaleido tiger logged into binance NFT on July 27, and has achieved good results in the first round

如何零代码制作深度学习的趣味app(适合新手)

Windows下cmd窗口连接mysql并操作表
随机推荐
学习、研究编程之道
Okaleido tiger logged into binance NFT on July 27, and has achieved good results in the first round
加密资产熊市之下,PlatoFarm的策略玩法依旧能获得稳定收益
Training log 6 of the project "construction of Shandong University mobile Internet development technology teaching website"
手撕ORM 框架(泛型+注解+反射)
新手入门:手把手从PHP环境到ThinkPHP6框架下载
“山东大学移动互联网开发技术教学网站建设”项目实训日志四
农村品牌建设给年轻人的一些机会
Starfish OS:以现实为纽带,打造元宇宙新范式
改哭了,终于解决了Cannot read properties of undefined (reading ‘parseComponent‘)
SQL修复重复数据
焕然一新,swagger UI 主题更改
ReportingService WebService Form身份验证
Synchronous development with open source projects & codereview & pull request & Fork how to pull the original warehouse
Move protocol global health declaration, carry out the health campaign to the end
Print out all prime numbers between 1-100
与张小姐的春夏秋冬(3)
华为2020校招笔试编程题 看这篇就够了(上)
C# 判断用户是手机访问还是电脑访问
Dao race track is booming. What are the advantages of m-dao?