最近整一些见不得人的事情,每天都忙到很晚。悲剧。
SELECT a.client_id,
s.cnt s_cnt,
a.cnt a_cnt,
s.cnt / a.cnt s_rate
FROM (SELECT COUNT(*) cnt,
handle_client client_id
FROM tb_captcha cpout
WHERE expire_time > curdate ()
GROUP BY handle_client) a
LEFT JOIN (SELECT COUNT(*),
handle_client
FROM tb_captcha
WHERE id IN (SELECT MAX(id)
FROM tb_captcha
WHERE task_id IN (SELECT task_id
FROM tb_client_task_log
WHERE task_code IN ('registerRobotUserEmail','registerWeibo')
AND status = 0
AND executed_time > '2011-03')
GROUP BY task_id,
seq)
GROUP BY handle_client;) s ON a.client_id = s.client_id
ORDER BY s.cnt DESC;
同事写了个子查询,跑到mysql上乖乖停不下来,最后被我kill掉了。
哥来优化一下。
先建索引
在tb_captcha建索引(expire_time, handle_client), (task_id)
在tb_client_log上建索引(status, execuited_time)
subquery很坑爹当成exists跑。都是all scan。
![0877b52edf072343c0a2ddcfbc67f9b0.png](https://img8.php1.cn/3cdc5/155f4/8fd/5834f4149c699cf6.jpeg)
查询后的的数据量太大,type为all
怎么改呢。
1.如果临时表不是很大,用临时表ok
2.用join代替子查询
用inner join优化最里面的子查询。
![f5ec487cedb0ff6c16d49adb9ad5044f.png](https://img8.php1.cn/3cdc5/155f4/8fd/402579f0cb3d8e77.jpeg)
可以看到里层已经将unique_dependency+all 优化成ref+range。测试性能有所提高,但是没有达到数量级的提高。大概提高了4,5倍。外面那个子查询还会将整个查询死掉。外面有个index type。
外部子查询用临时表优化
![2c7ff27c9babaa5db9353ddca6a3ac0f.png](https://img8.php1.cn/3cdc5/155f4/8fd/8e4874c02a67df0a.jpeg)
因为临时表都会比较小,所以这种方式对性能有很大的提高。
原来结果根本出不来。现在的执行时间是:
![57058cced602b2ad7e783aa143fc482d.png](https://img8.php1.cn/3cdc5/155f4/8fd/4e4304b4f232f25a.jpeg)
执行时间是10ms。
呵呵。应该算成功优化了。
再加上left join。
![ed5c8ff6bfb1691918bd1982800e0562.png](https://img8.php1.cn/3cdc5/155f4/8fd/872e3327888565dd.jpeg)
10ms。ok。
![a02efc6fa70e2b2bb41bb7ae59971aaa.png](https://img8.php1.cn/3cdc5/155f4/8fd/5d8d792ada1a3fc6.jpeg)
大小: 113 KB
![f54e1d7a0d402a9041491bd2117edb5b.png](https://img8.php1.cn/3cdc5/155f4/8fd/84d0f8c97fd6e2f9.jpeg)
大小: 111.5 KB
![1cac0734639ea21097ae26c3a7f16f9b.png](https://img8.php1.cn/3cdc5/155f4/8fd/53603cd8a59b7f0e.jpeg)
大小: 44.1 KB
![9decca542f054b200cc3ef5d44cfecc9.png](https://img8.php1.cn/3cdc5/155f4/8fd/e05355bebae3444b.jpeg)
大小: 76.9 KB
![e1df186540f9715107989e7c23b067dc.png](https://img8.php1.cn/3cdc5/155f4/8fd/05880bfe9a4fce92.jpeg)
大小: 96.6 KB
0
顶
0
踩
分享到:
![18e900b8666ce6f233d25ec02f95ee59.png](https://img8.php1.cn/3cdc5/155f4/8fd/f39e30e1b457a63a.jpeg)
![72dd548719f0ace4d5f9bca64e1d7715.png](https://img8.php1.cn/3cdc5/155f4/8fd/ef6847951696a411.jpeg)
2012-03-23 15:00
浏览 1437
分类:数据库
评论