当前位置:网站首页>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.

边栏推荐
- The completely decentralized programming mode does not need servers or IP, just like a aimless network extending everywhere
- Research and implementation of flash loan DAPP
- Under the bear market of encrypted assets, platofarm's strategy can still obtain stable income
- 加密资产熊市之下,PlatoFarm的策略玩法依旧能获得稳定收益
- Detailed steps of JDBC connection to database
- Huawei 2020 school recruitment written test programming questions read this article is enough (Part 2)
- PHP如何生成二维码?
- Flink connector Oracle CDC 实时同步数据到MySQL(Oracle12c)
- IDEA使用JDBC连接MySQL数据库个人详细教程
- 闪贷Dapp的调研及实现
猜你喜欢

农村品牌建设给年轻人的一些机会

Starfish OS:以现实为纽带,打造元宇宙新范式

D3.JS 纵向关系图(加箭头,连接线文字描述)

以‘智’提‘质|金融影像平台解决方案

XDFS&中国日报社在线协同编辑平台典型案例

熊市下PLATO如何通过Elephant Swap,获得溢价收益?

Shanzhai coin Shib has a US $548.6 million stake in eth whale's portfolio - traders should be on guard

Training log 7 of the project "construction of Shandong University mobile Internet development technology teaching website"

Fantom (FTM) 价格将在未来几天飙升 20%

北京宝德&TaoCloud共建信创之路
随机推荐
Changed crying, and finally solved cannot read properties of undefined (reading 'parsecomponent')
打印出1-100之间的所有质数
centos7 静默安装oracle
一文读懂Move2Earn项目——MOVE
Madonna "hellent" bought $1.3 million NFT boring ape, which is now considered too expensive
“山东大学移动互联网开发技术教学网站建设”项目实训日志五
Crypto giants all in metauniverse, and platofarm may break through
php写一个购买全网最低价的纸尿裤
Most PHP programmers don't understand how to deploy safe code
30 knowledge points that must be mastered in quantitative development [what is individual data]?
量化开发必掌握的30个知识点【什么是分笔逐笔数据】?
PHP如何生成二维码?
CMD window under Windows connects to MySQL and operates the table
"Shandong University mobile Internet development technology teaching website construction" project training log I
Differences between href and SRC
中海油集团,桌面云&网盘存储系统应用案例
麦当娜“Hellbent”购买130万美元的nft无聊猿,现在被认为太贵了
Okaleido tiger logged into binance NFT on July 27, and has achieved good results in the first round
Under the bear market of encrypted assets, platofarm's strategy can still obtain stable income
焕然一新,swagger UI 主题更改