1.什麼是行子查詢:
select t1.*,(select vn from t2 where t2.c.1=t1.c3 limit 1) where t1.cn='xxx' ....
類似每行通過一個子查詢來查詢獲的結果,都是行子查詢。
2.案例:
MySQL 版本:MySQL-5.6.16-log
原sql:
# Query_time: 20.769287 Lock_time: 0.000152 Rows_sent: 10 Rows_examined: 11665408 SET timestamp=1420020764; SELECT f3.id,f3.pin,f3.toUser,f3.content,f3.created_time,f3.modified_time,f3.imgUrl,f3.clientVersion,f3.deviceInfo,case WHEN f3.created_time>f3.reply_time or f3.reply_time is NULL THEN '0' ELSE '1' END as reply_status from (select f1.id,f1.pin,f1.toUser,f1.content,f1.created_time,f1.modified_time,f1.imgUrl,f1.clientVersion,f1.deviceInfo,(select f2.created_time from feedback_xx f2 where pin='SYSTEM' and f2.toUser=f1.pin order by f2.created_time desc limit 0,1) as reply_time FROM feedback_xx f1 GROUP BY f1.pin DESC ORDER BY f1.created_time DESC )f3 where 1=1 limit 0,10;
查詢20多秒出結果,原因是外表的每一行都要通過子查詢獲得結果。存在行子查詢:
select f2.created_time from feedback_info f2 where pin='SYSTEM' and f2.toUser=f1.pin order by f2.created_time desc limit 0,1;
通過left join方式改寫sql,目的減少內表的掃描次數。
優化成:
SELECT f3.id,f3.pin,f3.toUser,f3.content,f3.created_time,f3.modified_time,f3.imgUrl,f3.clientVersion,f3.deviceInfo,case WHEN f3.created_time>f3.reply_time or f3.reply_time is NULL THEN '0' ELSE '1' END as reply_status from(select f1.id,f1.pin,f1.toUser,f1.content,f1.created_time,f1.modified_time,f1.imgUrl,f1.clientVersion,f1.deviceInfo,f2.created_time as reply_time from feedback_xx f1 left join(select a.toUser,a.created_time from feedback_xx a where a.pin='SYSTEM' order by a.created_time desc)f2 on f1.pin=f2.toUser GROUP BY f1.pin DESC ORDER BY f1.created_time DESC)f3 where 1=1;
5274 rows in set (0.17 sec)
執行計劃:
+----+-------------+------------+------+---------------+-------------+---------+----------------+-------+----------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+------+---------------+-------------+---------+----------------+-------+----------------------------------------------------+ | 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 98773 | NULL | | 2 | DERIVED | f1 | ALL | idx_pin | NULL | NULL | NULL | 9846 | Using temporary; Using filesort | | 2 | DERIVED | <derived3> | ref | <auto_key0> | <auto_key0> | 194 | jrlicai.f1.pin | 10 | NULL | | 3 | DERIVED | a | ref | idx_pin | idx_pin | 194 | const | 2207 | Using index condition; Using where; Using filesort | +----+-------------+------------+------+---------------+-------------+---------+----------------+-------+----------------------------------------------------+
總結:在統計查詢中不要使用行子查詢,效率很低,一定要改寫成join 的方式。
附:2014 年最後一篇Blog,明年繼續......