阳光网驿-企业信息化交流平台【DTC零售连锁全渠道解决方案】

 找回密码
 注册

QQ登录

只需一步,快速开始

扫描二维码登录本站

手机号码,快捷登录

老司机
查看: 1213|回复: 0

[转帖] mysql中count(*)与count(col) 查询效率比较

[复制链接]
  • TA的每日心情
    开心
    2012-3-7 10:15
  • 签到天数: 11 天

    [LV.3]偶尔看看II

    发表于 2012-1-14 11:26:48 | 显示全部楼层 |阅读模式
    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(*) 明显多出数量级的时间。
    楼主热帖
    启用邀请码注册,提高发帖质量,建设交流社区
    您需要登录后才可以回帖 登录 | 注册

    本版积分规则

    快速回复 返回顶部 返回列表