MySQL的count(*), count(1), count(col_name)的区别

本文来自于:

https://dev.mysql.com/doc/refman/5.6/en/group-by-functions.html#function_count

https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_count

https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_count

目录

一、对于InnoDB

二、对于MyISAM


一、对于InnoDB

COUNT(col_name)

对于 查询结果集中的 每一行,如果 col_name 是 non-null,则加1,最后得到的数字 即为 COUNT(col_name)

 

COUNT(*) 和 COUNT(1)

    1. 查询结果集的 行数量 即为 COUNT(*)或COUNT(1),不关心 行null 或 行non-null

    2. 两者 不存在 任何的性能差距(InnoDB处理两者的方式完全一样)

MySQL 5.6, 5.7, 8.0的官方文档明确指出(之前老版本应该也是一样,但,没去翻其他版本的文档):

InnoDB handles SELECT COUNT(*) and SELECT COUNT(1) operations in the same way. There is no performance difference.

 

InnoDB处理 SELECT COUNT(*) 的方式

    1. 5.7.18之前,InnoDB通过扫描 聚集索引(clustered index) 来处理 SELECT COUNT(*)

    2. 5.7.18及以后

        a. InnoDB通过遍历 可用的最小的辅助索引(secondary index) 来处理 SELECT COUNT(*)

        b. 当不存在 辅助索引(secondary index)时,则通过 扫描聚集索引(clustered index) 来处理 SELECT COUNT(*)

如果索引记录并未完全装入buffer pool,处理 SELECT COUNT(*)还是需要花费点时间的,所以,如果并不需要 精确的COUNT数量,可以使用 SHOW TABLE STATUS

 

使用“InnoDB引擎,MySQL 5.6.23-72.1-log”来验证下

drop table  if exists `test_count`;
CREATE TABLE `test_count` (
   `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
   `var_col1` varchar(64),
   `var_col2` varchar(64),
   primary key `pk_id` (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='测试count函数';

insert into test_count(var_col1, var_col2) values ('a1', 'b');
insert into test_count(var_col1, var_col2) values (null, 'b');
insert into test_count(var_col1, var_col2) values (null, null);

select
count(1), -- 3
count(*), -- 3
count(var_col1), -- 1
count(var_col2), -- 2
-- count(var_col1, var_col2), 语法错误
count(distinct var_col1, var_col2) -- 1。只要某个列为null,则不包括
from test_count;

SHOW TABLE STATUS where name='test_count';

 

 

二、对于MyISAM

MyISAM COUNT(*)

MyISAM 为行数量 存储了一个确切数字,所以同时满足下面条件时,SELECT COUNT(*)非常快

    1. 只查询 单一一个表,且,

    2. 不查询 其他列,且,

    3. 不存在 WHERE 条件

例如:SELECT COUNT(*) FROM student; 非常快

 

MyISAM 的COUNT(1)

COUNT(1) is only subject to the same optimization if the first column is defined as NOT NULL

没看懂这是啥意思

 

Enjoy

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值