MySQL - count(1)、count(*)、count(列名) 執行區別

執行效果

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(字段)

兩者的主要區別

  • count(1) 會統計表中的所有的記錄數,包含字段爲null 的記錄。
  • count(字段) 會統計該字段在表中出現的次數,忽略字段爲null 的情況。即不統計字段爲null 的記錄。

 

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

執行效果上

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

執行效率上

  1. 列名爲主鍵,count(列名)會比count(1)快。
  2. 列名不爲主鍵,count(1)會比count(列名)快。
  3. 如果表多個列並且沒有主鍵,則 count(1) 的執行效率優於 count(*)。
  4. 如果有主鍵,則 select count(主鍵)的執行效率是最優的。
  5. 如果表只有一個字段,則 select count(*)最優。

 

實例分析

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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章