可能的重复:
select count(*) 和 select count(any_non_null_column) 之间有什么区别?
我听说人们普遍认为,在计算查询中的行数时,您不应该执行 a,COUNT(*)而应该对索引列进行计数。
我见过 DBA,在计算行数时,运行SELECT COUNT(1) FROM table;.
什么是1查询?
我试过输入其他数字 (2, 0, -1) 并且结果总是与使用 1 相同。
这只是一种快捷方式,而不是列出要计算的特定列吗?
使用常量与列出列名是否有任何性能差异?
我目前使用的是 MySQl 5.1.60。
jch*_*360 10
如果您输入 count(*)、count(1) 或 count("test") 它将给您相同的结果,因为 mysql 将计算行数,例如:
select count(fieldname) from table;
Run Code Online (Sandbox Code Playgroud)
将显示相同的结果
select count(*) from table;
Run Code Online (Sandbox Code Playgroud)
或者
select count(1) from table
mysql> select * from language;
+-------------+----------+---------------------+
| language_id | name | last_update |
+-------------+----------+---------------------+
| 1 | English | 2006-02-15 05:02:19 |
| 2 | Italian | 2006-02-15 05:02:19 |
| 3 | Japanese | 2006-02-15 05:02:19 |
| 4 | Mandarin | 2006-02-15 05:02:19 |
| 5 | French | 2006-02-15 05:02:19 |
| 6 | German | 2006-02-15 05:02:19 |
+-------------+----------+---------------------+
6 rows in set (0.00 sec)
mysql> select 1 from language;
+---+
| 1 |
+---+
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
+---+
6 rows in set (0.00 sec)
mysql> select 'anything'from language;
+----------+
| anything |
+----------+
| anything |
| anything |
| anything |
| anything |
| anything |
| anything |
+----------+
6 rows in set (0.00 sec)
mysql> select count(1), count(*), count('anything') from language;
+----------+----------+-------------------+
| count(1) | count(*) | count('anything') |
+----------+----------+-------------------+
| 6 | 6 | 6 |
+----------+----------+-------------------+
1 row in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
结果将是一个等于该表的行数的数字。
请注意,将不会计算空字段....
mysql> select original_language_id from film where original_language_id is null;
+----------------------+
| original_language_id |
+----------------------+
| NULL |
| NULL |
| NULL |
| NULL |
| NULL |
| NULL |
| NULL |
......
| NULL |
+----------------------+
1000 rows in set (0.00 sec)
mysql> select count(original_language_id) from film where original_language_id is null;
+-----------------------------+
| count(original_language_id) |
+-----------------------------+
| 0 |
+-----------------------------+
1 row in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
因此,如果您想计算行数,我认为 count(something) 是一个不错的选择
mysql> SELECT COUNT(1) FROM film;
+----------+
| COUNT(1) |
+----------+
| 1000 |
+----------+
1 row in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43550 次 |
| 最近记录: |