MySQL 中字串字段,在使用in時,沒有加引號時的效能陷阱

迷茫
發布: 2017-01-23 14:59:17
原創
1527 人瀏覽過

場景與環境

redhat6.5 + 64位元+ 12核心+ 16G

表數量600w

MySQL 5.0

問題描述了一個簡單

欄位是普通索引,varchar),由於拼裝sql的時候,沒有使用引號,導致出現大量慢查詢

問題SQL

select count(*) total from member_phone where phone in(1521xxx541,15845xxx412)
登入後複製

問題SQL和糾正過的寫法對比

執行時間

mysql> select count(*) total from member_phone where phone in(1521xxx541,15845xxx412);
+-------+
| total |
+-------+
|     1 | 
+-------+
1 row in set (2.76 sec)
mysql> select count(*) total from member_phone where phone in('1521xxx541','15845xxx412');
+-------+
| total |
+-------+
|     1 | 
+-------+
1 row in set (0.01 sec)
mysql> select count(*) total from member_phone where (phone='1521xxx541' or phone='15845xxx412');
+-------+
| total |
+-------+
|     1 | 
+-------+
1 row in set (0.00 sec)
登入後複製

總結

在三個類型的sql中,效率從高到低分別是or,in 添加了引號, in不加引號。在explain中看到不加引號時,顯示的用上了索引phone,type 變成了 index ,和全表掃描差不多了,只不過MySQL掃描時按索引的次序進行而不是行。

提醒

在where多個or,in中條件個數比較多,或者多個in 條件時,實際性能都比較差的。以上測試我個人僅在MySQL5.0測試,高版官方不知是否優化過。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!