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(*) 明显多出数量级的时间。
一直以为select count(col) 比 select count(*) 好,晕了!
y7Ll37 comment6 ,
wow powerful!
What an inspiration you are to us all.
All I can say is WOW!
Good points
Lovely thoughts!! My sentiments exactly!
Thank you my friend, you brought a tear to my eye.
Lovely Story.. More important are the comments.. so beautifully interpreted !!! God Bless You All !!
Thank you, enjoyed the stories, your comments and pictures very, very much.
Its really weird.
i like your attitude. i agree, it is so stylish just to be yourself.
Reading that quote makes me reflect that a magic moment is not only a moment in a day.
I love your imagination
Huh, okay )) Special