首页 > 数据库 > MySQL count(*) 与 count(col) 查询效率比较

MySQL count(*) 与 count(col) 查询效率比较

2009年03月31号
查看评论 发表评论 1,560次浏览

优化总结:

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(*) 明显多出数量级的时间。

类别数据库 标签
  1. howard shoes
    发表于 2010年07月25号 15时36分25秒 | 1楼

    Iam happy that you are updating this blog as well as the new one….oh yeah!

  2. cheap designer handbags
    发表于 2010年07月26号 12时04分57秒 | 2楼

    Very heartwarming.

  3. Chanel Handbags
    发表于 2010年07月30号 14时56分26秒 | 3楼

    Great post, and so very true.

评论页数:
1 2 109
  1. 目前没有通告
你必需 登陆 才能发表评论.