MySQL 中的 COUNT(id) 与 COUNT(*)

2021-12-30 00:00:00 sql count mysql

假设表中有一个主要字段id"(如速度等),以下查询之间是否存在差异?

Is there a difference between the following queries, assuming there is a primary field 'id' in the table (as in speed, etc)?

SELECT COUNT(id) 
  FROM table

对比

SELECT COUNT(*) 
  FROM table

推荐答案

我知道问题是关于 MySQL,但就其价值而言,建议将 count(*) 用于 Oracle:这表明这是特定于数据库的(请参阅上面来自 BalusC 的评论).由于许多数据库(MS-SQL、MySQL)都有保存各种类型元数据的信息模式表,如果一种语法只是查找一个容易获得的值,而另一种则直接访问该表,那么肯定会有差异.在一天结束时:尝试不同的选项,看看 EXPLAIN 告诉你在幕后发生了什么.

I know the question is about MySQL, but for what it's worth, count(*) is recommended for Oracle: which goes to show that this is database specific (see comment above from BalusC). Since a lot of databases (MS-SQL, MySQL) have information schema tables that hold various types of metadata, there are bound to be differences if one syntax is simply looking up a readily-available value, and another is going straight to the table. At the end of day: try different options, an see what EXPLAIN is telling you is going on behind the scenes.

相关文章