1. 程式人生 > 資料庫 >MySQL中count(*)、count(1)和count(col)的區別彙總

MySQL中count(*)、count(1)和count(col)的區別彙總

前言

count函式是用來統計表中或陣列中記錄的一個函式,count(*) 它返回檢索行的數目, 不論其是否包含 NULL值。最近感覺大家都在討論count的區別,那麼我也寫下吧:歡迎留言討論,話不多說了,來一起看看詳細的介紹吧。

1、表結構:

dba_jingjing@3306>[rds_test]>CREATE TABLE `test_count` (
 -> `c1` varchar(10) DEFAULT NULL,-> `c2` varchar(10) DEFAULT NULL,-> KEY `idx_c1` (`c1`)
 -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK,0 rows affected (0.11 sec)

2、插入測試資料:

dba_jingjing@3306>[rds_test]>insert into test_count values(1,10);
Query OK,1 row affected (0.03 sec)

dba_jingjing@3306>[rds_test]>insert into test_count values(abc,null);
ERROR 1054 (42S22): Unknown column 'abc' in 'field list'
dba_jingjing@3306>[rds_test]>insert into test_count values('abc',null);
Query OK,1 row affected (0.04 sec)

dba_jingjing@3306>[rds_test]>insert into test_count values(null,1 row affected (0.04 sec)

dba_jingjing@3306>[rds_test]>insert into test_count values('368rhf8fj',1 row affected (0.03 sec)

dba_jingjing@3306>[rds_test]>select * from test_count;
+-----------+------+
| c1  | c2 |
+-----------+------+
| 1   | 10 |
| abc  | NULL |
| NULL  | NULL |
| 368rhf8fj | NULL |
+-----------+------+
4 rows in set (0.00 sec)

測試:

dba_jingjing@3306>[rds_test]>select count(*) from test_count;
+----------+
| count(*) |
+----------+
|  4 |
+----------+
1 row in set (0.00 sec)
   EXPLAIN: {
  "query_block": {
   "select_id": 1,"message": "Select tables optimized away"
  1 row in set,1 warning (0.00 sec)
dba_jingjing@3306>[rds_test]>select count(1) from test_count;
+----------+
| count(1) |
+----------+
|  4 |
+----------+
1 row in set (0.00 sec)
   EXPLAIN: {
  "query_block": {
   "select_id": 1,1 warning (0.00 sec)
dba_jingjing@3306>[rds_test]>select count(c1) from test_count;
+-----------+
| count(c1) |
+-----------+
|   3 |
+-----------+
1 row in set (0.00 sec)
   "table": {
    "table_name": "test1","access_type": "index","key": "idx_c1","used_key_parts": [
     "c1"
    ],"key_length": "33",

那麼這裡面的"key_length": "33",為什麼是33呢,什麼是二級索引?見下節

count(*) 和count(1) 是沒有區別的,而count(col) 是有區別的

執行計劃有特點:可以看出它沒有查詢索引和表,有時候會出現select tables optimized away 不會查表,速度會很快

Extra有時候會顯示“Select tables optimized away”,意思是沒有更好的可優化的了。

官方解釋For explains on simple count queries (i.e. explain select count(*) from people) the extra
section will read "Select tables optimized away."
This is due to the fact that MySQL can read the result directly from the table internals and therefore does not need to perform the select.

---MySQL對於“Select tables optimized away”的含義,不是"沒有更好的可優化的了",官方解釋中關鍵的地方在於:
MySQL can read the result directly

所以,合理的解釋是:

1 資料已經在記憶體中可以直接讀取;

2 資料可以被認為是一個經計算後的結果,如函式或表示式的值;

3 一旦查詢的結果被優化器"預判"可以不經執行就可以得到結果,所以才有"not need to perform the select".

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對我們的支援。