SQL中 count(*)和count(1)的對比,區別


執行效果:


1.  count(1) and count(*)

當表的數據量大些時,對表作分析之后,使用count(1)還要比使用count(*)用時多了! 
從執行計划來看,count(1)和count(*)的效果是一樣的。 但是在表做過分析之后,count(1)會比count(*)的用時少些(1w以內數據量),不過差不了多少。 
 
如果count(1)是聚索引,id,那肯定是count(1)快。但是差的很小的。 
因為count(*),自動會優化指定到那一個字段。所以沒必要去count(1),用count(*),sql會幫你完成優化的 因此:count(1)和count(*)基本沒有差別! 
 
2. count(1) and count(字段)
兩者的主要區別是
(1) count(1) 會統計表中的所有的記錄數,包含字段為null 的記錄。
(2) count(字段) 會統計該字段在表中出現的次數,忽略字段為null 的情況。即不統計字段為null 的記錄。 
轉自:http://www.cnblogs.com/Dhouse/p/6734837.html


count(*) 和 count(1)和count(列名)區別  

執行效果上:  
count(*)包括了所有的列,相當於行數,在統計結果的時候,不會忽略列值為NULL  
count(1)包括了忽略所有列,用1代表代碼行,在統計結果的時候,不會忽略列值為NULL  
count(列名)只包括列名那一列,在統計結果的時候,會忽略列值為空(這里的空不是只空字符串或者0,而是表示null)的計數,即某個字段值為NULL時,不統計。

執行效率上:  
列名為主鍵,count(列名)會比count(1)快  
列名不為主鍵,count(1)會比count(列名)快  
如果表多個列並且沒有主鍵,則 count(1) 的執行效率優於 count(*)  
如果有主鍵,則 select count(主鍵)的執行效率是最優的  
如果表只有一個字段,則 select count(*)最優。
轉自:http://eeeewwwqq.iteye.com/blog/1972576


實例分析

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: 0

mysql> 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://blog.csdn.net/lihuarongaini/article/details/68485838


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM