当前位置:网站首页>MySql统计函数COUNT详解
MySql统计函数COUNT详解
2022-07-30 16:24:00 【m0_67392661】
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.

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦
边栏推荐
- 论文阅读 (63):Get To The Point: Summarization with Pointer-Generator Networks
- 新零售saas小程序如何探索数字化门店的破局之路?
- [NCTF2019]Fake XML cookbook-1|XXE漏洞|XXE信息介绍
- 大厂面试官眼中的好简历到底长啥样
- Wuhan Star Sets Sail: Overseas warehouse infrastructure has become a major tool for cross-border e-commerce companies to go overseas
- vivo announced to extend the product warranty period, the system launched a variety of functional services
- js 切换数据源的时候该缓存checkbox选中结果并回显?
- Moonbeam创始人解读多链新概念Connected Contract
- Login Module Debugging - Getting Started with Software Debugging
- 配置Path环境变量
猜你喜欢
随机推荐
(1) Cloud computing technology learning - virtualized vSphere learning
vivo宣布延长产品保修期限 系统上线多种功能服务
FME realizes the method of converting CAD with attribute to SHP data
hcip--ospf综合实验
基于STM32F407使用ADC采集电压实验
rhce笔记1
lotus 爆块失败
CMake库搜索函数居然不搜索LD_LIBRARY_PATH
The service already exists! Solution
华为云WeLink携手伙伴,共建协同办公生态
围绕用户思维,木鸟与途家如何实现乡村民宿下的用户运营
绕开驱动层检测的无痕注入
The way of life, share with you!
LeetCode-283-移动零
新技术要去做新价值
初识二叉搜索树
Moonbeam创始人解读多链新概念Connected Contract
Qt 容器控件Tool Box 使用详解
Redis 复习计划 - Redis 数据结构和持久化机制
huato 热更新环境搭建(DLL方式热更新C#代码)





![[NCTF2019]Fake XML cookbook-1|XXE漏洞|XXE信息介绍](/img/29/92b9d52d17a203b8bdead3eb2c902e.png)


![[AGC] Quality Service 1 - Example of Crash Service](/img/d8/e6b365889449745a61597b668dc89b.png)
