Do you really understand the count() function?

Reading this blog is expected to consume 5 minutes of your time [Phrase of the day]: What hurts you often benefits you a lot

count classification

 count(*)  最常用的一种,返回符合条件所有行
 count(1)  符合条件存在记录则返回数+1
 count(normal column) 统计符合条件记录某列字段非NULL值数量
 count(unique column) 统计符合条件记录某列唯一约束字段非NULL值数量
 count(primary) 统计符合条件记录主键数量

Performance comparison (for reference only)

count(1) >  count(*) > count(primary) > count(unique column) > count(normal column)

analyze

  根据mysql查询优化器规则,有索引的记录查询效率会更高,
  所以 count(primary) > count(unique column) > count(normal column) 应当是无异议的。
  
  那么,为什么count(*)count(1) 比其他count效率更高呢? 举个鲜活的例子,就好比数人头,是个人我们就算一个,
  我不用去观察目标人物是不是正常人,更不用去判断目标人物的性别,这两种都是属于统一性质的。
  
  在这有读者开始质疑我了,既然count(*)count(1)是同一性质的行为,那你是怎么判断count(1) > count(*)呢?
  我阅读很多篇关于count(*)count(1)性能讨论的文章,我说一下我个人的观点,
  我认为count(1)是有就返回,不关心列中存储的数据,而count(*)至少会检索一列,如果没有自增,又没有非空约束,
  那么就会判断column1是不是NULL,不是+1,否则继续判断column2,依次查询该记录所有列。
  
  另外还有一些方式来证实我的想法,如下图:
First, we obtain the number of rows in real time through the navicat client

insert image description here

Then view the results

insert image description here

Then we query the operation log, and the method of issuing navicat is the same as ours

insert image description here

Note, don't look at the number of rows in the detailed information, this is the data of mysql's internal statistics table, it seems that there is a cache mechanism, not real-time

insert image description here

I believe you have found the answer, hope this article can help you (●'◡'●)

Guess you like

Origin blog.csdn.net/qq_45903258/article/details/122361809