搜索
程序员 - MySQL统计数据count(*) 和 count(1) 什么区别??
黄舟
黄舟 2017-04-17 11:45:20
[MySQL讨论组]

MySQL统计数据count(*) 和 count(1) 什么区别??

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(7)
PHP中文网

没有区别.

mysql> explain extended select count(*) from tmp;
...
1 row in set, 1 warning (0.34 sec)

mysql> show warnings;
+-------+------+--------------------------------------------------+
| Level | Code | Message                                          |
+-------+------+--------------------------------------------------+
| Note  | 1003 | select count(0) AS `count(*)` from `test1`.`tmp` |
+-------+------+--------------------------------------------------+
1 row in set (0.00 sec)

http://dev.mysql.com/doc/refman/5.6/en/group-by-functions.html#function_count

COUNT(expr) Returns a count of the number of non-NULL values of expr in
the rows retrieved by a SELECT statement. ... COUNT(*) is somewhat different
in that it returns a count of the number of rows retrieved, whether or
not they contain NULL values.

阿神

1.查询数据结果集
没有区别
cite : http://stackoverflow.com/questions/3003457/count-vs-countcolumn-name-which-is-more-correct
2.性能区别
区别
记得看《sql 沉思者》中提及部分数据库对count(1)的优化
在部分数据库下,会对select count(1)做优化,导致select count(1) better than select count(*)

summary

看到这个问题,我不清楚mysql下是否存在相同的问题,所以做了一个查询工作
cite :http://www.phpddt.com/db/mysql-count-1.html

因为这里没有说明是mysql数据库,故而无法证明mysql下有同样的优化

然后我就继续google了,针对mysql镜像查询
cite :http://boards.straightdope.com/sdmb/showthread.php?t=455365
参看十五十六楼的回答,证实了 mysql 下 select (1) is faster than select(*)


建议查询的时候尽量使用select (1) 替代select (*)

天蓬老师

不好意思,第一次的回答确实错了,我试验一下,
1.count(1)count(*)是一样的,都返回包括null在内的值,1不是指的第一列!当然count(2)count(1)是一样的。
2.count(column)count(*)是不一样的,column是字段名,通过count(column)取出来的值是不包括null的。

呜呜,题主真是不好意思,差点误导你。

PHP中文网

我也一直想着count(*)和count(1)有什么区别,看来完全一样!了解了

PHP中文网

我记得count(1)只扫描主键Index就可以得到数据,count(*)是扫描表的,效率上有所不同,其他就如上面的所说,与count(column)关于Null的判断

PHP中文网

count(*)count(1)一样,楼主如果要统计,建议用count(主键)的方式!

怪我咯

count(*):只要一行记录不全是null,都是可以统计的
count(1):都是可以统计的

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号