(转载)原文地址:https://blog.csdn.net/sinat_37167645/article/details/86143176
业务场景:需要关联表删除多行数据,一个表的数据在百万级,一个表在十万级,两个表均有索引,简化的表结构如下:
原始SQL:
DELETE FROM delete_1 WHERE id IN (SELECT b.id FROM delete_2 b WHERE b.res_type = 'A' AND res_code = 13);
查看执行计划:
两表均有索引(原表在百万级,测试表只有几行数据),但是并未使用有效索引,导致删除时造成锁超时
优化1:使用表别名,可以不修改原SQL语意
DELETE a FROM delete_1 a WHERE a.id IN (SELECT b.id FROM delete_2 b WHERE b.res_type = 'A' AND res_code = 11);
查看执行计划:
优化2:将IN改为"=",这将更改原意,业务中发现改为"="也符合实际情况,视自己业务而定
DELETE FROM delete_1 WHERE id = (SELECT b.id FROM delete_2 b WHERE b.res_type = 'A' AND b.res_code = 11);
查看执行计划:
总结:
数据库大佬都建议表加别名,那就加上吧!!!那就加上吧!!!那就加上吧!!!