1. 程式人生 > 其它 >id returned 1 exit status是什麼錯誤_mysql 中count(1) count(*) count(col_name)區別

id returned 1 exit status是什麼錯誤_mysql 中count(1) count(*) count(col_name)區別

技術標籤:id returned 1 exit status是什麼錯誤

mysql 中count(1) count(*) count(col_name)區別

這三個在innodb中有什麼區別嗎(這裡我們前提都是沒有where條件的,如果有where條件則按實際情況有所不同)?

首先我們對一個表進行查詢

select count(*) ,count(1),count(recomm_user_id) from user ;
2f1592d58dad1b18f45d1e6b9b9191ca.png

從上面我們得出 統計的區別是

count(*) count(1) 都是統計結果的行數

count(列名) 則是統計該列不為null的條數

效能對比

count(col_name)的執行計劃如下

explainselect count(address) from user ;
6dbf1091e96812804fda452d9dd64a70.png

結論:count(col_name) 這個不一定走索引,可能需要全表掃描

count(1) count(*)執行計劃如下

 explain select count(1) from user;explain select count(*) from user ;
2e6f3b7e672137726f9dc95f258093a5.png

我們看到,這兩個執行計劃都一樣,都是走索引,而且我們看到mysql 是對這個進行過優化的,並不是做主鍵索引,而是走最小的索引。我們把索引列出來看下

PRIMARY KEY (`user_id`) USING BTREE,

UNIQUE KEY `idx_user_mobile` (`mobile`) USING BTREE,

KEY `idx_user_status` (`status`) USING BTREE,

KEY `recomm_user_id` (`recomm_user_id`) USING BTREE

在這四個索引中 欄位型別分別如下,

user _id bigint

mobile varchar(20)

status int

recomm_user_id bigint

第一個 user_id 為bigint 並且是主鍵,比較大 不使用

mobile 是 varchar(20) 字串比較大

status int 最小的索引(也是使用這個,因為它最小)

recomm_user_id bigint

通過對比,status 為 int ,最小,所以也是使用這個來進行統計,

如果我們在給該表新增一個更小的索引,是不是就會用更小的索引呢? 我們找到該表studio_status 該欄位為bit 比 int還小,新增完成後為我們在count 下看看效果

63a7e32055d90d505e6fefd57b134042.png

我們看到,統計已經使用更小的索引 studio_status 了