码迷,mamicode.com
首页 > 数据库 > 详细

使用SQL命令的in&not in等删除数据的总结

时间:2020-04-22 13:26:47      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:href   code   series   color   log   优化   not   结合   mod   

总结:
1、查询时用 not in 效率极其低下,因此结合left join改为in查询,效率很快

原语句:

 select * from my_test_table where id not in (select b.id as id from ( SELECT MAX(a.`ModifyAt`)ModifyAt,a.userid FROM my_test_table a   GROUP BY a.UserId,a.SeriesId,a.CourseId) c
 INNER JOIN `my_test_table` b ON c.userid=b.userid AND c.ModifyAt=b.ModifyAt)

优化后:

select * from (select u.id as id from my_test_table u left join  (select b.id as id from ( SELECT MAX(a.`ModifyAt`)ModifyAt,a.userid FROM my_test_table a   GROUP BY a.UserId,a.SeriesId,a.CourseId) c
 INNER JOIN `my_test_table` b ON c.userid=b.userid AND c.ModifyAt=b.ModifyAt) d  on d.id = u.id where d.Id is null) as e

2、查询出后,需要用 delete where in 来删除,但是delete where in 语句效率极其低下。

原语句:

delete from my_test_table where id in (select * from (select u.id as id from my_test_table u left join  (select b.id as id from ( SELECT MAX(a.`ModifyAt`)ModifyAt,a.userid FROM my_test_table a   GROUP BY a.UserId,a.SeriesId,a.CourseId) c
 INNER JOIN `my_test_table` b ON c.userid=b.userid AND c.ModifyAt=b.ModifyAt) d  on d.id = u.id where d.Id is null) as e)

因此改为where语句,关联表删除数据 优化后:

delete deluser from my_test_table deluser,(select * from (select u.id as id from my_test_table u left join  (select b.id as id from ( SELECT MAX(a.`ModifyAt`)ModifyAt,a.userid FROM my_test_table a   GROUP BY a.UserId,a.SeriesId,a.CourseId) c
 INNER JOIN `my_test_table` b ON c.userid=b.userid AND c.ModifyAt=b.ModifyAt) d  on d.id = u.id where d.Id is null) as e) f where deluser.id = f.id;

0.36秒执行完成。

 

参考文章:

https://blog.csdn.net/hello_l/article/details/71419464

https://blog.csdn.net/pcwblover008/article/details/80015855

使用SQL命令的in&not in等删除数据的总结

标签:href   code   series   color   log   优化   not   结合   mod   

原文地址:https://www.cnblogs.com/dayang12525/p/12751123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!