当前位置:网站首页>Detailed explanation of MySQL statistical function count
Detailed explanation of MySQL statistical function count
2022-07-29 05:58:00 【Benben's coriander】
MySql Statistical function COUNT Detailed explanation
- 1. COUNT() Function Overview
- 2. COUNT() Parameter description
- 3. COUNT() To judge the existence of
- 4. COUNT() Ali Development Specification
1. COUNT() Function Overview
COUNT() It's an aggregate function , Returns the number of rows matching the specified criteria . In development, it is often used to count the data in the table , All data , Not for NULL data , Or de duplication data .
2. COUNT() Parameter description
COUNT(1): Statistics are not NULL The record of .
COUNT(*): Count all the records ( Include NULL).
COUNT( Field ): Statistics should " Field " Not for NULL The record of .
1. If this field is defined as not null Words , Read the field line by line from the record , Judgment cannot be null, Add by line .
2. If the field definition allows null Words , To judge that it might be null, Also take out the value and judge , No null Just add up .
COUNT(DISTINCT Field ): Statistics should " Field " Weight removal without NULL The record of .
-- MySql Statistical function count test
-- Create a user table , New test data
CREATE TABLE `user` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID Primary key ',
`name` varchar(64) DEFAULT NULL COMMENT ' full name ',
`sex` varchar(8) DEFAULT NULL COMMENT ' Gender ',
`age` int(4) DEFAULT NULL COMMENT ' Age ',
`born` date DEFAULT NULL COMMENT ' Date of birth ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT=' User table ';
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (1, '% Zhang San %', ' male ', 22, '2022-04-22');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (2, ' Li Si ', ' Woman ', 12, '2022-04-01');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (3, ' Wang Xiaoer ', ' Woman ', 12, '2022-04-28');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (4, ' Zhao si ', ' male ', 23, '2022-04-28');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (5, '', ' Woman ', 23, '2022-04-28');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (6, NULL, ' Woman ', 60, '2022-04-28');
INSERT INTO `category`.`user`(`id`, `name`, `sex`, `age`, `born`) VALUES (7, NULL, ' Woman ', 61, '2022-04-28');
select * from user;
-- statistics :7 Data , Count all the records ( Include NULL).
select count(*) from user;
-- statistics :7 Data , Statistics are not NULL The record of .
select count(1) from user;
-- statistics :5 Data ,COUNT( Field ): Statistics should " Field " Not for NULL The record of , Note that null Not empty '' character string
select count(name) from user;
-- statistics :5 Data ,COUNT(DISTINCT Field ): Statistics should " Field " Weight removal without NULL The record of .
select count(distinct name) from user;
3. COUNT() To judge the existence of
SQL No longer use count, Instead, use LIMIT 1, Let the database query to return when encountering an item , Don't keep looking for how many more , In the business code, you can directly judge whether it is not empty .
select 1 from emp LIMIT 1; Efficiency is the highest , Especially the need for limit Limit the number of rows , It's easy to ignore .
-- SQL Find out if " There is "
-- The employee table , Delete if it exists
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
);
-- newly added cehsi data
Test data :https://blog.csdn.net/m0_37583655/article/details/124385347
-- cahxun
select * from emp ;
-- Time :1.082s, data :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
-- Time :1.129s, data :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
-- Time :1.695s, data :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 No longer use count, Instead, use LIMIT 1, Let the database query to return when encountering an item , Don't keep looking for how many more , In the business code, you can directly judge whether it is not empty
-- Time :0.001s, data :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() Ali Development Specification
1.【 mandatory 】 Do not use count( Name ) or count( Constant ) To replace count(),count() yes SQL92 The standard of definition Syntax of quasi statistical line number , It's not about the database , Follow NULL He Fei NULL irrelevant . explain :count(*) The statistical value is NULL The line of , and count( Name ) This column is not counted NULL Row of values .
2.【 mandatory 】count(distinct col) Calculate the column Division NULL Number of non repeating lines outside , Be careful count(distinct col1, col2) If one of the columns is all NULL, So even if the other column has different values , Also returned as 0.

边栏推荐
- mysql插入百万数据(使用函数和存储过程)
- Xsan is highly available - xdfs and San are integrated with new vitality
- Super simple integration HMS ml kit face detection to achieve cute stickers
- Android Studio 实现登录注册-源代码 (连接MySql数据库)
- SQL repair duplicate data
- 并发编程学习笔记 之 工具类CountDownLatch、CyclicBarrier详解
- Under the bear market of encrypted assets, platofarm's strategy can still obtain stable income
- Novice introduction: download from PHP environment to thinkphp6 framework by hand
- 微信内置浏览器禁止缓存的问题
- “山东大学移动互联网开发技术教学网站建设”项目实训日志七
猜你喜欢

Ribbon学习笔记二

day02作业之进程管理

SSM integration

ReportingService WebService Form身份验证

Laravel swagger add access password

How can Plato obtain premium income through elephant swap in a bear market?

Strategic cooperation with many institutions shows the strength of the leading company of platofarm yuancosmos

How to PR an open source composer project

Simple optimization of interesting apps for deep learning (suitable for novices)

Flutter正在被悄悄放弃?浅析Flutter的未来
随机推荐
MySql统计函数COUNT详解
IDEA中设置自动build-改动代码,不用重启工程,刷新页面即可
Extreme deflation and perpetual motion machine model will promote the outbreak of platofarm
Activity交互问题,你确定都知道?
主流实时流处理计算框架Flink初体验。
Breaking through the hardware bottleneck (I): the development of Intel Architecture and bottleneck mining
DCAT batch operation popup and parameter transfer
【go】defer的使用
Win10+opencv3.2+vs2015 configuration
Study and research the way of programming
Lock lock of concurrent programming learning notes and its implementation basic usage of reentrantlock, reentrantreadwritelock and stampedlock
并发编程学习笔记 之 原子操作类AtomicInteger详解
Flink connector Oracle CDC 实时同步数据到MySQL(Oracle19c)
ssm整合
day02 作业之文件权限
"Shandong University mobile Internet development technology teaching website construction" project training log V
“山东大学移动互联网开发技术教学网站建设”项目实训日志五
微信内置浏览器禁止缓存的问题
突破硬件瓶颈(一):Intel体系架构的发展与瓶颈挖掘
Mobile terminal -flex item attribute