MySQL · 性能優化 · MySQL常見SQL錯誤用法
前言
MySQL在2016年仍然保持強勁的資料庫流行度增長趨勢。越來越多的客戶將自己的應用建立在MySQL資料庫之上,甚至是從Oracle遷移到MySQL上來。但也存在部分客戶在使用MySQL資料庫的過程中遇到一些比如響應時間慢,CPU打滿等情況。阿里雲RDS專家服務團隊幫助雲上客戶解決過很多緊急問題。現將《ApsaraDB專家診斷報告》中出現的部分常見SQL問題總結如下,供大家參考。
常見SQL錯誤用法
1. LIMIT 語句
分頁查詢是最常用的場景之一,但也通常也是最容易出問題的地方。比如對於下面簡單的語句,一般DBA想到的辦法是在type, name, create_time欄位上加組合索引。這樣條件排序都能有效的利用到索引,性能迅速提升。
SELECT * nFROM operation nWHERE type = SQLStats n AND name = SlowLog nORDER BY create_time nLIMIT 1000, 10; n
好吧,可能90%以上的DBA解決該問題就到此為止。但當 LIMIT 子句變成 「LIMIT 1000000,10」 時,程序員仍然會抱怨:我只取10條記錄為什麼還是慢?
要知道資料庫也並不知道第1000000條記錄從什麼地方開始,即使有索引也需要從頭計算一次。出現這種性能問題,多數情形下是程序員偷懶了。在前端數據瀏覽翻頁,或者大數據分批導出等場景下,是可以將上一頁的最大值當成參數作為查詢條件的。SQL重新設計如下:
SELECT * nFROM operation nWHERE type = SQLStats nAND name = SlowLog nAND create_time > 2017-03-16 14:00:00 nORDER BY create_time limit 10;n
在新設計下查詢時間基本固定,不會隨著數據量的增長而發生變化。
2. 隱式轉換
SQL語句中查詢變數和欄位定義類型不匹配是另一個常見的錯誤。比如下面的語句:
mysql> explain extended SELECT * n > FROM my_balance b n > WHERE b.bpn = 14000000123 n > AND b.isverified IS NULL ;nmysql> show warnings;n| Warning | 1739 | Cannot use ref access on index bpn due to type or collation conversion on field bpnn
其中欄位bpn的定義為varchar(20),MySQL的策略是將字元串轉換為數字之後再比較。函數作用於表欄位,索引失效。
上述情況可能是應用程序框架自動填入的參數,而不是程序員的原意。現在應用框架很多很繁雜,使用方便的同時也小心它可能給自己挖坑。
3. 關聯更新、刪除
雖然MySQL5.6引入了物化特性,但需要特別注意它目前僅僅針對查詢語句的優化。對於更新或刪除需要手工重寫成JOIN。
比如下面UPDATE語句,MySQL實際執行的是循環/嵌套子查詢(DEPENDENT SUBQUERY),其執行時間可想而知。
UPDATE operation o nSET status = applying nWHERE o.id IN (SELECT id n FROM (SELECT o.id, n o.status n FROM operation o n WHERE o.group = 123 n AND o.status NOT IN ( done ) n ORDER BY o.parent, n o.id n LIMIT 1) t); n
執行計劃:
+----+--------------------+-------+-------+---------------+---------+---------+-------+------+-----------------------------------------------------+n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |n+----+--------------------+-------+-------+---------------+---------+---------+-------+------+-----------------------------------------------------+n| 1 | PRIMARY | o | index | | PRIMARY | 8 | | 24 | Using where; Using temporary |n| 2 | DEPENDENT SUBQUERY | | | | | | | | Impossible WHERE noticed after reading const tables |n| 3 | DERIVED | o | ref | idx_2,idx_5 | idx_5 | 8 | const | 1 | Using where; Using filesort |n+----+--------------------+-------+-------+---------------+---------+---------+-------+------+-----------------------------------------------------+n
重寫為JOIN之後,子查詢的選擇模式從DEPENDENT SUBQUERY變成DERIVED,執行速度大大加快,從7秒降低到2毫秒。
UPDATE operation o n JOIN (SELECT o.id, n o.status n FROM operation o n WHERE o.group = 123 n AND o.status NOT IN ( done ) n ORDER BY o.parent, n o.id n LIMIT 1) tn ON o.id = t.id nSET status = applying n
執行計劃簡化為:
+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |n+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+n| 1 | PRIMARY | | | | | | | | Impossible WHERE noticed after reading const tables |n| 2 | DERIVED | o | ref | idx_2,idx_5 | idx_5 | 8 | const | 1 | Using where; Using filesort |n+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+n
4. 混合排序
MySQL不能利用索引進行混合排序。但在某些場景,還是有機會使用特殊方法提升性能的。
SELECT * nFROM my_order o n INNER JOIN my_appraise a ON a.orderid = o.id nORDER BY a.is_reply ASC, n a.appraise_time DESC nLIMIT 0, 20 n
執行計劃顯示為全表掃描:
+----+-------------+-------+--------+-------------+---------+---------+---------------+---------+-+n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra n+----+-------------+-------+--------+-------------+---------+---------+---------------+---------+-+n| 1 | SIMPLE | a | ALL | idx_orderid | NULL | NULL | NULL | 1967647 | Using filesort |n| 1 | SIMPLE | o | eq_ref | PRIMARY | PRIMARY | 122 | a.orderid | 1 | NULL |n+----+-------------+-------+--------+---------+---------+---------+-----------------+---------+-+n
由於is_reply只有0和1兩種狀態,我們按照下面的方法重寫後,執行時間從1.58秒降低到2毫秒。
SELECT * nFROM ((SELECT *n FROM my_order o n INNER JOIN my_appraise a n ON a.orderid = o.id n AND is_reply = 0 n ORDER BY appraise_time DESC n LIMIT 0, 20) n UNION ALL n (SELECT *n FROM my_order o n INNER JOIN my_appraise a n ON a.orderid = o.id n AND is_reply = 1 n ORDER BY appraise_time DESC n LIMIT 0, 20)) t nORDER BY is_reply ASC, n appraisetime DESC nLIMIT 20; n
5. EXISTS語句
MySQL對待EXISTS子句時,仍然採用嵌套子查詢的執行方式。如下面的SQL語句:
SELECT *nFROM my_neighbor n n LEFT JOIN my_neighbor_apply sra n ON n.id = sra.neighbor_id n AND sra.user_id = xxx nWHERE n.topic_status < 4 n AND EXISTS(SELECT 1 n FROM message_info m n WHERE n.id = m.neighbor_id n AND m.inuser = xxx) n AND n.topic_type <> 5 n
執行計劃為:
+----+--------------------+-------+------+-----+------------------------------------------+---------+-------+---------+ -----+n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |n+----+--------------------+-------+------+ -----+------------------------------------------+---------+-------+---------+ -----+n| 1 | PRIMARY | n | ALL | | NULL | NULL | NULL | 1086041 | Using where |n| 1 | PRIMARY | sra | ref | | idx_user_id | 123 | const | 1 | Using where |n| 2 | DEPENDENT SUBQUERY | m | ref | | idx_message_info | 122 | const | 1 | Using index condition; Using where |n+----+--------------------+-------+------+ -----+------------------------------------------+---------+-------+---------+ -----+n
去掉exists更改為join,能夠避免嵌套子查詢,將執行時間從1.93秒降低為1毫秒。
SELECT *nFROM my_neighbor n n INNER JOIN message_info m n ON n.id = m.neighbor_id n AND m.inuser = xxx n LEFT JOIN my_neighbor_apply sra n ON n.id = sra.neighbor_id n AND sra.user_id = xxx nWHERE n.topic_status < 4 n AND n.topic_type <> 5 n
新的執行計劃:
+----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |n+----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+n| 1 | SIMPLE | m | ref | | idx_message_info | 122 | const | 1 | Using index condition |n| 1 | SIMPLE | n | eq_ref | | PRIMARY | 122 | ighbor_id | 1 | Using where |n| 1 | SIMPLE | sra | ref | | idx_user_id | 123 | const | 1 | Using where |n+----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+n
6. 條件下推
外部查詢條件不能夠下推到複雜的視圖或子查詢的情況有:
- 聚合子查詢;
- 含有LIMIT的子查詢;
- UNION 或UNION ALL子查詢;
- 輸出欄位中的子查詢;
如下面的語句,從執行計劃可以看出其條件作用於聚合子查詢之後:
SELECT * nFROM (SELECT target, n Count(*) n FROM operation n GROUP BY target) t nWHERE target = rm-xxxx n
+----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |n+----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+n| 1 | PRIMARY | <derived2> | ref | <auto_key0> | <auto_key0> | 514 | const | 2 | Using where |n| 2 | DERIVED | operation | index | idx_4 | idx_4 | 519 | NULL | 20 | Using index |n+----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+n
確定從語義上查詢條件可以直接下推後,重寫如下:
SELECT target, n Count(*) nFROM operation nWHERE target = rm-xxxx nGROUP BY targetn
執行計劃變為:
+----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |n+----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+n| 1 | SIMPLE | operation | ref | idx_4 | idx_4 | 514 | const | 1 | Using where; Using index |n+----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+n
關於MySQL外部條件不能下推的詳細解釋說明請參考以前文章:MySQL · 性能優化 · 條件下推到物化表
7. 提前縮小範圍
先上初始SQL語句:
SELECT * nFROM my_order o n LEFT JOIN my_userinfo u n ON o.uid = u.uidn LEFT JOIN my_productinfo p n ON o.pid = p.pid nWHERE ( o.display = 0 ) n AND ( o.ostaus = 1 ) nORDER BY o.selltime DESC nLIMIT 0, 15 n
該SQL語句原意是:先做一系列的左連接,然後排序取前15條記錄。從執行計劃也可以看出,最後一步估算排序記錄數為90萬,時間消耗為12秒。
+----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |n+----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+n| 1 | SIMPLE | o | ALL | NULL | NULL | NULL | NULL | 909119 | Using where; Using temporary; Using filesort |n| 1 | SIMPLE | u | eq_ref | PRIMARY | PRIMARY | 4 | o.uid | 1 | NULL |n| 1 | SIMPLE | p | ALL | PRIMARY | NULL | NULL | NULL | 6 | Using where; Using join buffer (Block Nested Loop) |n+----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+n
由於最後WHERE條件以及排序均針對最左主表,因此可以先對my_order排序提前縮小數據量再做左連接。SQL重寫後如下,執行時間縮小為1毫秒左右。
SELECT * nFROM (nSELECT * nFROM my_order o nWHERE ( o.display = 0 ) n AND ( o.ostaus = 1 ) nORDER BY o.selltime DESC nLIMIT 0, 15n) o n LEFT JOIN my_userinfo u n ON o.uid = u.uid n LEFT JOIN my_productinfo p n ON o.pid = p.pid nORDER BY o.selltime DESCnlimit 0, 15n
再檢查執行計劃:子查詢物化後(select_type=DERIVED)參與JOIN。雖然估算行掃描仍然為90萬,但是利用了索引以及LIMIT 子句後,實際執行時間變得很小。
+----+-------------+------------+--------+---------------+---------+---------+-------+--------+----------------------------------------------------+n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |n+----+-------------+------------+--------+---------------+---------+---------+-------+--------+----------------------------------------------------+n| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 15 | Using temporary; Using filesort |n| 1 | PRIMARY | u | eq_ref | PRIMARY | PRIMARY | 4 | o.uid | 1 | NULL |n| 1 | PRIMARY | p | ALL | PRIMARY | NULL | NULL | NULL | 6 | Using where; Using join buffer (Block Nested Loop) |n| 2 | DERIVED | o | index | NULL | idx_1 | 5 | NULL | 909112 | Using where |n+----+-------------+------------+--------+---------------+---------+---------+-------+--------+----------------------------------------------------+n
8. 中間結果集下推
再來看下面這個已經初步優化過的例子(左連接中的主表優先作用查詢條件):
SELECT a.*, n c.allocated nFROM ( n SELECT resourceid n FROM my_distribute d n WHERE isdelete = 0 n AND cusmanagercode = 1234567 n ORDER BY salecode limit 20) a nLEFT JOIN n ( n SELECT resourcesid, sum(ifnull(allocation, 0) * 12345) allocated n FROM my_resources n GROUP BY resourcesid) c nON a.resourceid = c.resourcesidn
那麼該語句還存在其它問題嗎?不難看出子查詢 c 是全表聚合查詢,在表數量特別大的情況下會導致整個語句的性能下降。
其實對於子查詢 c,左連接最後結果集只關心能和主表resourceid能匹配的數據。因此我們可以重寫語句如下,執行時間從原來的2秒下降到2毫秒。
SELECT a.*, n c.allocated nFROM ( n SELECT resourceid n FROM my_distribute d n WHERE isdelete = 0 n AND cusmanagercode = 1234567 n ORDER BY salecode limit 20) a nLEFT JOIN n ( n SELECT resourcesid, sum(ifnull(allocation, 0) * 12345) allocated n FROM my_resources r, n ( n SELECT resourceid n FROM my_distribute d n WHERE isdelete = 0 n AND cusmanagercode = 1234567 n ORDER BY salecode limit 20) a n WHERE r.resourcesid = a.resourcesid n GROUP BY resourcesid) c nON a.resourceid = c.resourcesidn
但是子查詢 a 在我們的SQL語句中出現了多次。這種寫法不僅存在額外的開銷,還使得整個語句顯的繁雜。使用WITH語句再次重寫:
WITH a AS n( n SELECT resourceid n FROM my_distribute d n WHERE isdelete = 0 n AND cusmanagercode = 1234567 n ORDER BY salecode limit 20)nSELECT a.*, n c.allocated nFROM a nLEFT JOIN n ( n SELECT resourcesid, sum(ifnull(allocation, 0) * 12345) allocated n FROM my_resources r, n a n WHERE r.resourcesid = a.resourcesid n GROUP BY resourcesid) c nON a.resourceid = c.resourcesidn
AliSQL即將推出WITH語法,敬請期待。
總結
- 資料庫編譯器產生執行計劃,決定著SQL的實際執行方式。但是編譯器只是儘力服務,所有資料庫的編譯器都不是盡善盡美的。上述提到的多數場景,在其它資料庫中也存在性能問題。了解資料庫編譯器的特性,才能避規其短處,寫出高性能的SQL語句。
- 程序員在設計數據模型以及編寫SQL語句時,要把演算法的思想或意識帶進來。
- 編寫複雜SQL語句要養成使用WITH語句的習慣。簡潔且思路清晰的SQL語句也能減小資料庫的負擔 ^^。
- 使用雲上資料庫遇到難點(不局限於SQL問題),隨時尋求阿里雲原廠專家服務的幫助。
更多資料庫相關技術文章:
PgSQL · 特性分析 · Write-Ahead Logging機制淺析
MSSQL · 特性分析 · 列存儲技術做實時分析
推薦閱讀:
※MySQL訓練——Using NULL@sqlzoo.net
※4.5 資料庫表-博客後端Api-NodeJs+Express+Mysql實戰
※MySQL資料庫的高可用性分析
※MySQL | AND運算符
※MySQL成數據勒索新目標,開發4步自查