面试官 | count(1)、count(*) 、count(列名) 有什么区别?
作者 | BigoSprite
來源 | 39sd.cn/0926A
先看執(zhí)行效果:
1.? count(1) and count(*)
當表的數(shù)據(jù)量大些時,對表作分析之后,使用count(1)還要比使用count(*)用時多了!?
從執(zhí)行計劃來看,count(1)和count(*)的效果是一樣的。但是在表做過分析之后,count(1)會比count(*)的用時少些(1w以內(nèi)數(shù)據(jù)量),不過差不了多少。?
如果count(1)是聚索引,id,那肯定是count(1)快。但是差的很小的。?
因為count(*),自動會優(yōu)化指定到那一個字段。所以沒必要去count(1),用count(*),sql會幫你完成優(yōu)化的 因此:count(1)和count(*)基本沒有差別!?
2. count(1) and count(字段)
兩者的主要區(qū)別是
count(1) 會統(tǒng)計表中的所有的記錄數(shù),包含字段為null 的記錄。
count(字段) 會統(tǒng)計該字段在表中出現(xiàn)的次數(shù),忽略字段為null 的情況。即不統(tǒng)計字段為null 的記錄。?
count(*) 和 count(1)和count(列名)區(qū)別??
執(zhí)行效果上:?
?
count(*)包括了所有的列,相當于行數(shù),在統(tǒng)計結(jié)果的時候,不會忽略列值為NULL??
count(1)包括了忽略所有列,用1代表代碼行,在統(tǒng)計結(jié)果的時候,不會忽略列值為NULL??
count(列名)只包括列名那一列,在統(tǒng)計結(jié)果的時候,會忽略列值為空(這里的空不是只空字符串或者0,而是表示null)的計數(shù),即某個字段值為NULL時,不統(tǒng)計。
執(zhí)行效率上:??
列名為主鍵,count(列名)會比count(1)快??
列名不為主鍵,count(1)會比count(列名)快??
如果表多個列并且沒有主鍵,則 count(1) 的執(zhí)行效率優(yōu)于 count(*)??
如果有主鍵,則 select count(主鍵)的執(zhí)行效率是最優(yōu)的??
如果表只有一個字段,則 select count(*)最優(yōu)。
實例分析
mysql> create table counttest(name char(1), age char(2)); Query OK, 0 rows affected (0.03 sec)mysql> insert into counttest values-> ('a', '14'),('a', '15'), ('a', '15'),-> ('b', NULL), ('b', '16'),-> ('c', '17'),-> ('d', null),->('e', ''); Query OK, 8 rows affected (0.01 sec) Records: 8 Duplicates: 0 Warnings: 0mysql> select * from counttest; +------+------+ | name | age | +------+------+ | a | 14 | | a | 15 | | a | 15 | | b | NULL | | b | 16 | | c | 17 | | d | NULL | | e | | +------+------+ 8 rows in set (0.00 sec) mysql> select name, count(name), count(1), count(*), count(age), count(distinct(age))-> from counttest-> group by name; +------+-------------+----------+----------+------------+----------------------+ | name | count(name) | count(1) | count(*) | count(age) | count(distinct(age)) | +------+-------------+----------+----------+------------+----------------------+ | a | 3 | 3 | 3 | 3 | 2 | | b | 2 | 2 | 2 | 1 | 1 | | c | 1 | 1 | 1 | 1 | 1 | | d | 1 | 1 | 1 | 0 | 0 | | e | 1 | 1 | 1 | 1 | 1 | +------+-------------+----------+----------+------------+----------------------+ 5 rows in set (0.00 sec)參考:
http://www.cnblogs.com/Dhouse/p/6734837.html
http://eeeewwwqq.iteye.com/blog/1972576
http://blog.csdn.net/lihuarongaini/article/details/68485838
【END】
近期熱文
面試珍藏:最常見的200多道Java面試題
被一個熟悉的面試題問懵了:String...
面試官:如何實現(xiàn)冪等性校驗?
關(guān)注下方二維碼,訂閱更多精彩內(nèi)容
朕已閱?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的面试官 | count(1)、count(*) 、count(列名) 有什么区别?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 经典面试题 | 讲一下垃圾回收器都有哪些
- 下一篇: 第 2-1 课:类与 Object +