MYSQL count(*) 和 count(1) 哪个更好?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5179969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:58:15  来源:igfitidea点击:

What is better in MYSQL count(*) or count(1)?

mysqlsqlperformance

提问by Tomasz Smykowski

Related (SQL Server):Count(*) vs Count(1)

相关(SQL Server):Count(*) vs Count(1)

Could you please tell me what is better in performance (MySQL)? Count(*) or count(1)?

你能告诉我什么是更好的性能(MySQL)?计数(*)还是计数(1)?

回答by RichardTheKiwi

This is a MySQL answer.

这是一个 MySQL 答案。

They perform exactly the same - unless you are using MyISAM, then a special case for COUNT(*)exists. I always use COUNT(*)anyway.

它们的性能完全相同 - 除非您使用的是 MyISAM,否则COUNT(*)存在一个特殊情况。COUNT(*)反正我总是用。

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

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

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:

如果 SELECT 从一个表中检索,没有检索到其他列,并且没有 WHERE 子句,则 COUNT(*) 被优化为非常快速地返回。例如:

mysql> SELECT COUNT(*) FROM student;

This optimization applies only to MyISAM tables only, because an exact row count is stored for this storage engine and can be accessed very quickly. For transactional storage engines such as InnoDB, storing an exact row count is more problematic because multiple transactions may be occurring, each of which may affect the count.

此优化仅适用于 MyISAM 表,因为此存储引擎存储了准确的行数,并且可以非常快速地访问。对于 InnoDB 等事务性存储引擎,存储一个精确的行数问题更大,因为可能会发生多个事务,每个事务都可能影响计数。



EDIT

编辑

Some of you may have missed the dark attempt at humour. I prefer to keep this as a non-duplicate question for any such day when MySQL will do something different to SQL Server. So I threw a vote to reopen the question (with a clearly wrong answer).

你们中的一些人可能错过了幽默的黑暗尝试。我更愿意将此作为一个非重复的问题,以便 MySQL 对 SQL Server 做一些不同的事情。所以我投票重新提出这个问题(答案显然是错误的)。

The above MyISAM optimization applies equally to

上述 MyISAM 优化同样适用于

COUNT(*)
COUNT(1)
COUNT(pk-column)
COUNT(any-non-nullable-column)

So the real answer is that they are alwaysthe same.

所以真正的答案是它们总是相同的。