Home > Database > Mysql Tutorial > Mysql优化之select count效率_MySQL

Mysql优化之select count效率_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 13:45:37
Original
850 people have browsed it

bitsCN.com

 

1.任何情况下SELECT COUNT(*) FROM tablename是最优选择;

2.尽量减少SELECT COUNT(*) FROM tablename WHERE COL = ‘value’ 这种查询;

3.杜绝SELECT COUNT(COL) FROM tablename的出现。

 

 

COUNT(*)与COUNT(COL)

网上搜索了下,发现各种说法都有:

比如认为COUNT(COL)比COUNT(*)快的;

认为COUNT(*)比COUNT(COL)快的;

还有朋友很搞笑的说到这个其实是看人品的。

在不加WHERE限制条件的情况下,COUNT(*)与COUNT(COL)基本可以认为是等价的;

但是在有WHERE限制条件的情况下,COUNT(*)会比COUNT(COL)快非常多;

具体的数据参考如下:

mysql> SELECT COUNT(*) FROM cdb_posts where fid = 604;

+————+

| COUNT(fid) |

+————+

| 79000 |

+————+

1 row in set (0.03 sec)

mysql> SELECT COUNT(tid) FROM cdb_posts where fid = 604;

+————+

| COUNT(tid) |

+————+

| 79000 |

+————+

1 row in set (0.33 sec)

mysql> SELECT COUNT(pid) FROM cdb_posts where fid = 604;

+————+

| COUNT(pid) |

+————+

| 79000 |

+————+

1 row in set (0.33 sec)

COUNT(*)通常是对主键进行索引扫描,而COUNT(COL)就不一定了,另外前者是统计表中的所有符合的纪录总数,而后者是计算表中所有符合的COL的纪录数。还有有区别的。

COUNT时的WHERE

简单说下,就是COUNT的时候,如果没有WHERE限制的话,MySQL直接返回保存有总的行数

而在有WHERE限制的情况下,总是需要对MySQL进行全表遍历。

优化总结:

1.任何情况下SELECT COUNT(*) FROM tablename是最优选择;

2.尽量减少SELECT COUNT(*) FROM tablename WHERE COL = ‘value’ 这种查询;

3.杜绝SELECT COUNT(COL) FROM tablename的出现。

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template