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

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

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


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 (*)


没有区别.

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.


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


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

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


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


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


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

【热门文章】
【热门文章】