分享到:
发表于 2009-08-30 21:39:05 楼主 | |
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(*) 明显多出数量级的时间。 |
|
楼主热贴
个性签名:无
|
发表于 2009-08-30 23:06:49 1楼 | |
学习了 支持 | |
发表于 2009-11-30 13:02:22 2楼 | |
原来如此i,谢谢楼主分享 | |
发表于 2009-12-31 23:29:36 3楼 | |
顶 | |
针对ZOL星空(中国)您有任何使用问题和建议 您可以 联系星空(中国)管理员 、 查看帮助 或 给我提意见