MySQL count(*) 与 count(col) 查询效率比较
优化总结:
1.任何情况下SELECT COUNT(*) FROM xxx 是最优选择;
2.尽量减少SELECT
COUNT(*) FROM xxx WHERE COL = ‘xxx’ 这种查询;
3.杜绝SELECT COUNT(COL) FROM tablename WHERE COL = ‘xxx’
的出现。(其中COL非主键)
环境:
MySQL版本:5.0.45
OS:Windows XP SP3
数
据表一:sphinx
+———-+——————+——+—–+———+—————-+
| Field |
Type | Null | Key | Default | Extra |
+———-+——————+——+—–+———+—————-+
|
id | int(10) unsigned | NO | PRI | NULL | auto_increment |
|
til | varchar(100) | NO | | | |
|
content | text | NO | | | |
|
dataline | int(11) | NO | | | |
+———-+——————+——+—–+———+—————-+
记
录数:1120100
查询一:
mysql>
select count(*) as totalnum from sphinx;
+———-+
| totalnum |
+———-+
|
1120100 |
+———-+
1 row in set (0.00 sec
)
查询二:
mysql> select count(*) as
totalnum from sphinx where id>1000;
+———-+
| totalnum |
+———-+
|
1119100 |
+———-+
1 row in set (2.17 sec
)
查询三:
mysql> select count(*) as
totalnum from sphinx where id>1000;
+———-+
| totalnum |
+———-+
|
1119100 |
+———-+
1 row in set (0.61 sec
)
查询四:
mysql> select count(*) as
totalnum from sphinx where id>1000;
+———-+
| totalnum |
+———-+
|
1119100 |
+———-+
1 row in set (0.61 sec
)
查询五:
mysql> select count(id) as
totalnum from sphinx;
+———-+
| totalnum |
+———-+
| 1120100 |
+———-+
1
row in set (0.00 sec
)
查
询六:
mysql> select count(til) as totalnum from sphinx where
id>1000;
+———-+
| totalnum |
+———-+
| 1119100 |
+———-+
1
row in set (1 min 38.61 sec
)
查
询七:
mysql> select count(id) as totalnum from sphinx where
id>11000;
+———-+
| totalnum |
+———-+
| 1109100 |
+———-+
1
row in set (0.61 sec
)
查
询八:
mysql> select count(id) as totalnum from sphinx;
+———-+
|
totalnum |
+———-+
| 1120100 |
+———-+
1 row in set (0.03 sec
)
结论:
在
select count() 没有 where 条件的时候 select count(*) 和 select count(col)
所消耗的查询时间相差无几。
在 select count() 有 where 条件的时候 select count(col)
所消耗的查询时间 比 select count(*) 明显多出数量级的时间。
我测试了一下,并不完全像这篇文章所言!数据量为320万