使用SQL命令的in¬ in等刪除數據的總結


總結:
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM