欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL Execution Plan--COUNT相关测试

程序员文章站 2022-04-16 21:37:59
COUNT全表记录 在MySQL中,相同的SQL不同的存储引擎执行计划不同: 现有测试表TB101: 对于没有WHERE条件的COUNT(*)/COUNT(1)/COUNT(ID)/COUNT(C1)的执行计划为: 对于没有WHERE条件的COUNT(C2)的执行计划为: 可以发现,对于MyISAM ......

count全表记录

在mysql中,相同的sql不同的存储引擎执行计划不同:

对于myisam引擎,由于使用表锁进行并发控制,同一时间点多个并发线程执行相同查询获得的结果相同,且myisam存储引擎专门存储表总记录数,因此使用count(*)查询全表记录时能直接返回。

而对于innodb存储引擎,由于使用mvcc和行锁进行并发控制,同一时间点多个并发线程执行相同查询获得的结果存在差异(每个回话的readview不同),且没有专门存储表总记录数,因此每次查询都需要扫描全表或扫描某个索引的全部记录。

for transactional storage engines such as innodb, storing an exact row count is problematic. multiple transactions may be occurring at the same time, each of which may affect the count.

innodb does not keep an internal count of rows in a table because concurrent transactions might “see” different numbers of rows at the same time. consequently, select count(*) statements only count rows visible to the current transaction.

prior to mysql 5.7.18, innodb processes select count(*) statements by scanning the clustered index. as of mysql 5.7.18, innodb processes select count(*) statements by traversing the smallest available secondary index unless an index or optimizer hint directs the optimizer to use a different index. if a secondary index is not present, the clustered index is scanned.

processing select count(*) statements takes some time if index records are not entirely in the buffer pool. for a faster count, create a counter table and let your application update it according to the inserts and deletes it does. however, this method may not scale well in situations where thousands of concurrent transactions are initiating updates to the same counter table. if an approximate row count is sufficient, use show table status.

innodb handles select count(*) and select count(1) operations in the same way. there is no performance difference.

for myisam tables, count(*) is optimized to return very quickly if the select retrieves from one table, no other columns are retrieved, and there is no where clause.

this optimization only applies to myisam tables, because an exact row count is stored for this storage engine and can be accessed very quickly. count(1) is only subject to the same optimization if the first column is defined as not null。

现有测试表tb101:

create table `tb101` (
  `id` int(11) not null auto_increment,
  `c1` int(11) not null,
  `c2` int(11) default null,
  primary key (`id`)
) engine=myisam auto_increment=140001 default charset=utf8

对于没有where条件的count(*)/count(1)/count(id)/count(c1)的执行计划为:

mysql> explain select count(*) from tb101 \g
*************************** 1. row ***************************
           id: 1
  select_type: simple
        table: null
   partitions: null
         type: null
possible_keys: null
          key: null
      key_len: null
          ref: null
         rows: null
     filtered: null
        extra: select tables optimized away
1 row in set, 1 warning (0.00 sec)

对于没有where条件的count(c2)的执行计划为:

mysql> explain select count(c2) from tb101 \g
*************************** 1. row ***************************
           id: 1
  select_type: simple
        table: tb101
   partitions: null
         type: all
possible_keys: null
          key: null
      key_len: null
          ref: null
         rows: 140000
     filtered: 100.00
        extra: null
1 row in set, 1 warning (0.00 sec)

可以发现,对于myisam存储引擎,在没有where条件下,如果c1列为not null,则可以将count(c1)与count(*)和count(1)做相同的处理。

针对上面的测试,对于innodb存储引擎,在没有where条件下:

1、id列为not null主键,count(id)和count(1)或count(*)的执行计划相同,返回结果相同。

2、c1列为not null,count(c1)和count(1)或count(*)的执行结果相同,但执行计划不同。

 

 

count(expr)异同

1、count(1)和count(*)等价,两者在执行计划和执行效率上完全相同。

个人推荐使用count(1)替换count(*),原因是简单直观,
他人推荐使用count(1),原因是符合sql92标准,阿里巴巴java开发手册推荐。

 

2、count(*)和count(c1)不一定等价,两者执行计划和执行结果会存在差异。

count(*):执行返回满足where条件的行数,不考虑null值问题
count(c1): 执行返回满足where条件且c1不等于null的行数,不统计c1等于null的行。

换种理解思路:
对于myisam引擎表和innodb引擎表,无论是显式主键还是因此rowid,都要求非空唯一,每行记录都肯定存在一个不为null的列(列组),因此计算count(*)时不需要考虑null值问题。

 

一个有趣的扩展,如果c1为not null,那么count(c1)与count(1)的返回结果相同,那么mysql会对此进行优化么?

现有测试表结果如下:

create table `tb01` (
  `id` int(11) not null auto_increment,
  `c1` int(11) not null,
  `c2` int(11) not null,
  primary key (`id`),
  key `idx_c2` (`c2`)
) engine=innodb auto_increment=16384 default charset=utf8

查看count(*)和count(c1)的执行计划:

mysql> explain select count(*) from tb01 where c2<100 \g
*************************** 1. row ***************************
           id: 1
  select_type: simple
        table: tb01
   partitions: null
         type: range
possible_keys: idx_c2
          key: idx_c2
      key_len: 4
          ref: null
         rows: 99
     filtered: 100.00
        extra: using where; using index
1 row in set, 1 warning (0.00 sec)

mysql> explain select count(c1) from tb01 where c2<100 \g
*************************** 1. row ***************************
           id: 1
  select_type: simple
        table: tb01
   partitions: null
         type: range
possible_keys: idx_c2
          key: idx_c2
      key_len: 4
          ref: null
         rows: 99
     filtered: 100.00
        extra: using index condition
1 row in set, 1 warning (0.00 sec)

从上面执行计划可以发现,在处理count(*)时,仅需要使用idx_c2即可完成查询,因此extra为using index,而在处理count(c1)时,需要使用idx_c2进行过滤后再执行回表查询,因此extra为using index condition。

针对上面的测试,myisam存储引擎和innodb存储引擎的测试结果相同。

 

count(distinc ...)操作

mysql官网解释为:

count(distinct expr,[expr...])

returns a count of the number of rows with different non-null expr values.

in mysql, you can obtain the number of distinct expression combinations that do not contain null by giving a list of expressions. in standard sql, you would have to do a concatenation of all expressions inside count(distinct ...).

在mysql中允许执行:

select count(distinct id,c1) from tb02;

但不允许执行:

select count(id,c1) from tb02;

 

总结

1、对于innodb和myisam存储引擎,count(1)和count(*)在任何场景下都等价,执行性能和执行计划相同。

2、在查询全表记录(没有where条件)时,对于myisam存储引擎,存储引擎存储表总记录数,无需扫描数据因此查询可以很快返回,对于innodb存储引擎,需要扫描全表或某个索引的全部记录因此查询可能比较耗时。

3、对于myisam存储引擎,在没有where条件情况下,如果列c1为not null,那么count(c1)和count(*)执行操作相同。

4、对于innodb存储引擎,如果列c1为主键,那么count(c1)和count(*)执行计划和执行效率相同,如果c1为not null,那么count(c1)和count(*)执行计划和执行效率不一定相同,只有在查询使用c1列上索引时才可能相同。

 

参考链接:

https://mp.weixin.qq.com/s/iohvtel2klni-ol4ubivbq