一、直入正题
两者一样快!
Mysql官方文档有明确说明,原文链接如下:
https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_count
所有讨论,针对Mysql5.7版本。
二、InnoDB和MyISAM有些不同
1、InnoDB
官方文档这么写的:
InnoDB handles SELECT COUNT(*) and SELECT COUNT(1) operations in the same way. There is no performance difference.
意思是:
InnoDB 存储引擎对select count(*)和select count(1)两者的操作控制方式是一样的。它们没有性能上的差别。
2、MyISAM
官方文档这么写的:
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. For example:
mysql> SELECT COUNT(*) FROM student;
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.
意思是:
MyISAM 存储引擎在执行查询的时候,查询优化器优化了COUNT(*)和COUNT(1)操作。因为MyISAM存储引擎是记录行号的,查询的时候直接返回了行号,所以执行的非常快。
不过直接返回行号的优化,对两者的要求不同:
①COUNT(*)要满足没有where条件;
②COUNT(1)没有where条件可以,在有where条件时,满足首列有非空属性依然可以。
三、where条件
在加了where条件的时候两者的快慢,其实在同一储引擎中,两者仍然是一样的。
之前我看过不少博主讨论,where条件中如果被检索的列如果加了索引,速度会提升。
那是必然啊,加了索引本身就是提升检索效率的,这里不做赘述。
四、其他
作为一个研发,要养成参考官方文档的习惯。
Copyright © 2018 Ansel. All rights reserved.