mysql 索引巧用,SQL語句寫得忒野了
今天來分享幾個MySQL常見的SQL錯誤**(不當)用法。我們在作為一個初學者時,很有可能自己在寫SQL時也沒有注意到這些問題,導致寫出來的SQL語句效率低下,所以我們也可以自省自檢一下。
1. LIMIT 語句
分頁查詢是最常用的場景之一,但也通常也是最容易出問題的地方。比如對於下面簡單的語句,一般DBA想到的辦法是在type, name, create_time欄位上加組合索引。這樣條件排序都能有效的利用到索引,效能迅速提升。
SELECT *
FROM operation
WHERE type = 'SQLStats'
AND name = 'SlowLog'
ORDER BY create_time
LIMIT 1000, 10;
好吧,可能90%以上的DBA解決該問題就到此為止。但當 LIMIT 子句變成 “LIMIT 1000000,10” 時,程式設計師仍然會抱怨:我只取10條記錄為什麼還是慢?
要知道資料庫也並不知道第1000000條記錄從什麼地方開始,即使有索引也需要從頭計算一次。出現這種效能問題,多數情形下是程式設計師偷懶了。在前端資料瀏覽翻頁,或者大資料分批匯出等場景下,是可以將上一頁的最大值當成引數作為查詢條件的。SQL重新設計如下:
SELECT *
FROM operation
WHERE type = 'SQLStats'
AND name = 'SlowLog'
AND create_time > '2017-03-16 14:00:00'
ORDER BY create_time limit 10;
在新設計下查詢時間基本固定,不會隨著資料量的增長而發生變化。
2. 隱式轉換
SQL語句中查詢變數和欄位定義型別不匹配是另一個常見的錯誤。比如下面的語句:
mysql> explain extended SELECT *
> FROM my_balance b
> WHERE b.bpn = 14000000123
> AND b.isverified IS NULL ;
mysql> show warnings;
| Warning | 1739 | Cannot use ref access on index 'bpn' due to type or collation conversion on field 'bpn'
其中欄位bpn的定義為varchar(20),MySQL的策略是將字串轉換為數字之後再比較。函式作用於表欄位,索引失效。
上述情況可能是應用程式框架自動填入的引數,而不是程式設計師的原意。現在應用框架很多很繁雜,使用方便的同時也小心它可能給自己挖坑。
3. 關聯更新、刪除
雖然MySQL5.6引入了物化特性,但需要特別注意它目前僅僅針對查詢語句的優化。對於更新或刪除需要手工重寫成JOIN。
比如下面UPDATE語句,MySQL實際執行的是迴圈/巢狀子查詢(DEPENDENT SUBQUERY),其執行時間可想而知。
UPDATE operation o
SET status = 'applying'
WHERE o.id IN (SELECT id
FROM (SELECT o.id,
o.status
FROM operation o
WHERE o.group = 123
AND o.status NOT IN ( 'done' )
ORDER BY o.parent,
o.id
LIMIT 1) t);
執行計劃:
+----+--------------------+-------+-------+---------------+---------+---------+-------+------+-----------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-------+-------+---------------+---------+---------+-------+------+-----------------------------------------------------+
| 1 | PRIMARY | o | index | | PRIMARY | 8 | | 24 | Using where; Using temporary |
| 2 | DEPENDENT SUBQUERY | | | | | | | | Impossible WHERE noticed after reading const tables |
| 3 | DERIVED | o | ref | idx_2,idx_5 | idx_5 | 8 | const | 1 | Using where; Using filesort |
+----+--------------------+-------+-------+---------------+---------+---------+-------+------+-----------------------------------------------------+
重寫為JOIN之後,子查詢的選擇模式從DEPENDENT SUBQUERY變成DERIVED,執行速度大大加快,從7秒降低到2毫秒。
UPDATE operation o
JOIN (SELECT o.id,
o.status
FROM operation o
WHERE o.group = 123
AND o.status NOT IN ( 'done' )
ORDER BY o.parent,
o.id
LIMIT 1) t
ON o.id = t.id
SET status = 'applying'
執行計劃簡化為:
+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+
| 1 | PRIMARY | | | | | | | | Impossible WHERE noticed after reading const tables |
| 2 | DERIVED | o | ref | idx_2,idx_5 | idx_5 | 8 | const | 1 | Using where; Using filesort |
+----+-------------+-------+------+---------------+-------+---------+-------+------+-----------------------------------------------------+
4. 混合排序
MySQL不能利用索引進行混合排序。但在某些場景,還是有機會使用特殊方法提升效能的。
SELECT *
FROM my_order o
INNER JOIN my_appraise a ON a.orderid = o.id
ORDER BY a.is_reply ASC,
a.appraise_time DESC
LIMIT 0, 20
執行計劃顯示為全表掃描:
+----+-------------+-------+--------+-------------+---------+---------+---------------+---------+-+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
+----+-------------+-------+--------+-------------+---------+---------+---------------+---------+-+
| 1 | SIMPLE | a | ALL | idx_orderid | NULL | NULL | NULL | 1967647 | Using filesort |
| 1 | SIMPLE | o | eq_ref | PRIMARY | PRIMARY | 122 | a.orderid | 1 | NULL |
+----+-------------+-------+--------+---------+---------+---------+-----------------+---------+-+
由於is_reply只有0和1兩種狀態,我們按照下面的方法重寫後,執行時間從1.58秒降低到2毫秒。
SELECT *
FROM ((SELECT *
FROM my_order o
INNER JOIN my_appraise a
ON a.orderid = o.id
AND is_reply = 0
ORDER BY appraise_time DESC
LIMIT 0, 20)
UNION ALL
(SELECT *
FROM my_order o
INNER JOIN my_appraise a
ON a.orderid = o.id
AND is_reply = 1
ORDER BY appraise_time DESC
LIMIT 0, 20)) t
ORDER BY is_reply ASC,
appraisetime DESC
LIMIT 20;
5. EXISTS語句
MySQL對待EXISTS子句時,仍然採用巢狀子查詢的執行方式。如下面的SQL語句:
SELECT *
FROM my_neighbor n
LEFT JOIN my_neighbor_apply sra
ON n.id = sra.neighbor_id
AND sra.user_id = 'xxx'
WHERE n.topic_status < 4
AND EXISTS(SELECT 1
FROM message_info m
WHERE n.id = m.neighbor_id
AND m.inuser = 'xxx')
AND n.topic_type <> 5
執行計劃為:
+----+--------------------+-------+------+-----+------------------------------------------+---------+-------+---------+ -----+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-------+------+ -----+------------------------------------------+---------+-------+---------+ -----+
| 1 | PRIMARY | n | ALL | | NULL | NULL | NULL | 1086041 | Using where |
| 1 | PRIMARY | sra | ref | | idx_user_id | 123 | const | 1 | Using where |
| 2 | DEPENDENT SUBQUERY | m | ref | | idx_message_info | 122 | const | 1 | Using index condition; Using where |
+----+--------------------+-------+------+ -----+------------------------------------------+---------+-------+---------+ -----+
去掉exists更改為join,能夠避免巢狀子查詢,將執行時間從1.93秒降低為1毫秒。
SELECT *
FROM my_neighbor n
INNER JOIN message_info m
ON n.id = m.neighbor_id
AND m.inuser = 'xxx'
LEFT JOIN my_neighbor_apply sra
ON n.id = sra.neighbor_id
AND sra.user_id = 'xxx'
WHERE n.topic_status < 4
AND n.topic_type <> 5
新的執行計劃:
+----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+
| 1 | SIMPLE | m | ref | | idx_message_info | 122 | const | 1 | Using index condition |
| 1 | SIMPLE | n | eq_ref | | PRIMARY | 122 | ighbor_id | 1 | Using where |
| 1 | SIMPLE | sra | ref | | idx_user_id | 123 | const | 1 | Using where |
+----+-------------+-------+--------+ -----+------------------------------------------+---------+ -----+------+ -----+
6. 條件下推
外部查詢條件不能夠下推到複雜的檢視或子查詢的情況有:
- 聚合子查詢;
- 含有LIMIT的子查詢;
- UNION 或UNION ALL子查詢;
- 輸出欄位中的子查詢;
如下面的語句,從執行計劃可以看出其條件作用於聚合子查詢之後:
SELECT *
FROM (SELECT target,
Count(*)
FROM operation
GROUP BY target) t
WHERE target = 'rm-xxxx'
+----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+
| 1 | PRIMARY | <derived2> | ref | <auto_key0> | <auto_key0> | 514 | const | 2 | Using where |
| 2 | DERIVED | operation | index | idx_4 | idx_4 | 519 | NULL | 20 | Using index |
+----+-------------+------------+-------+---------------+-------------+---------+-------+------+-------------+
確定從語義上查詢條件可以直接下推後,重寫如下:
SELECT target,
Count(*)
FROM operation
WHERE target = 'rm-xxxx'
GROUP BY target
執行計劃變為:
+----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+
| 1 | SIMPLE | operation | ref | idx_4 | idx_4 | 514 | const | 1 | Using where; Using index |
+----+-------------+-----------+------+---------------+-------+---------+-------+------+--------------------+
7. 提前縮小範圍
先上初始SQL語句:
SELECT *
FROM my_order o
LEFT JOIN my_userinfo u
ON o.uid = u.uid
LEFT JOIN my_productinfo p
ON o.pid = p.pid
WHERE ( o.display = 0 )
AND ( o.ostaus = 1 )
ORDER BY o.selltime DESC
LIMIT 0, 15
該SQL語句原意是:先做一系列的左連線,然後排序取前15條記錄。從執行計劃也可以看出,最後一步估算排序記錄數為90萬,時間消耗為12秒。
+----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+
| 1 | SIMPLE | o | ALL | NULL | NULL | NULL | NULL | 909119 | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | u | eq_ref | PRIMARY | PRIMARY | 4 | o.uid | 1 | NULL |
| 1 | SIMPLE | p | ALL | PRIMARY | NULL | NULL | NULL | 6 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+--------+---------------+---------+---------+-----------------+--------+----------------------------------------------------+
由於最後WHERE條件以及排序均針對最左主表,因此可以先對my_order排序提前縮小資料量再做左連線。SQL重寫後如下,執行時間縮小為1毫秒左右。
SELECT *
FROM (
SELECT *
FROM my_order o
WHERE ( o.display = 0 )
AND ( o.ostaus = 1 )
ORDER BY o.selltime DESC
LIMIT 0, 15
) o
LEFT JOIN my_userinfo u
ON o.uid = u.uid
LEFT JOIN my_productinfo p
ON o.pid = p.pid
ORDER BY o.selltime DESC
limit 0, 15
再檢查執行計劃:子查詢物化後(select_type=DERIVED)參與JOIN。雖然估算行掃描仍然為90萬,但是利用了索引以及LIMIT 子句後,實際執行時間變得很小。
+----+-------------+------------+--------+---------------+---------+---------+-------+--------+----------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+--------+---------------+---------+---------+-------+--------+----------------------------------------------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 15 | Using temporary; Using filesort |
| 1 | PRIMARY | u | eq_ref | PRIMARY | PRIMARY | 4 | o.uid | 1 | NULL |
| 1 | PRIMARY | p | ALL | PRIMARY | NULL | NULL | NULL | 6 | Using where; Using join buffer (Block Nested Loop) |
| 2 | DERIVED | o | index | NULL | idx_1 | 5 | NULL | 909112 | Using where |
+----+-------------+------------+--------+---------------+---------+---------+-------+--------+------------
相關文章
- SQL Server中巧用另類寫法代替Like語句SQLServer
- MySQL中常用SQL語句的編寫MySql
- 【MySQL】經典資料庫SQL語句編寫練習題——SQL語句掃盲MySql資料庫
- MySql 常用Sql語句MySql
- 列出oracle dbtime得sql語句OracleSQL
- MySQL建立索引、修改索引、刪除索引的命令語句MySql索引
- 《MySQL慢查詢優化》之SQL語句及索引優化MySql優化索引
- MYSQL SQL語句優化MySql優化
- mysql捕捉所有SQL語句MySql
- sql 語句練習 In MySQLMySql
- mysql 語句的索引和優化MySql索引優化
- sql語句抄寫作業SQL
- 如何寫這個sql語句?SQL
- ASP中巧用Split()函式生成SQL查詢語句 (轉)函式SQL
- 如何匯出MySQL索引的建立語句MySql索引
- MySQL利用索引優化ORDER BY排序語句MySql索引優化排序
- MySQL基本sql語句總結MySql
- mysql 常用sql語句 簡介MySql
- MySQL之SQL語句優化MySql優化
- MySQL中常用的SQL語句MySql
- MySql與Sql Server Update語句MySqlServer
- MYSQL 常用sql語句小結MySql
- mysql sql語句學習(一)MySql
- sql 語句練習(3) In MySQLMySql
- [zt] 基於索引的SQL語句優化索引SQL優化
- SQL語句規範的寫法SQL
- OCI插入SQL語句的寫法SQL
- 一條SQL語句的書寫SQL
- mybatis 得sql語句對應簡單型別MyBatisSQL型別
- MySQL DML語句書寫建議MySql
- MySQL指南之SQL語句基礎MySql
- MySql常用操作SQL語句彙總MySql
- mysql執行sql語句過程MySql
- mysql的sql語句執行流程MySql
- mysql空間大小的SQL語句MySql
- mysql 查詢建表語句sqlMySql
- MySQL管理之SQL語句例項MySql
- jsp tomcat mysql *SQL*語句JSTomcatMySql