Very slow delete on mysql base with subquery

前端 未结 4 547
星月不相逢
星月不相逢 2021-01-04 12:35

This mysql query is running for around 10 hours and has not finished. Something is horribly wrong.

Two tables (text and spam) are here. Spam stores the ids of spam e

相关标签:
4条回答
  • 2021-01-04 12:56

    of corse it will take a lot of time because it execute the subquery for every record but by using INNER JOIN directly this query is executed only one time lets think that the query will take

    10 ms for 50000 rec  full time = 50000 * 10 ms ---> 8.333 minutes !! at least don't forget the condition and deleting time .....
    

    but using join the query will be executed only one time :

    DELETE t FROM tname.text t INNER JOIN (SELECT textid FROM spam) sq on t.old_id = sq.textid ;
    
    0 讨论(0)
  • 2021-01-04 13:05

    Copy rows that are not in spam form text to new table. Then delete text table and rename created table. Good idea is not to add any keys to created table. Add keys after renaming.

    0 讨论(0)
  • 2021-01-04 13:07

    In my experience sub queries are often a cause of slow execution times in SQL statements, therefor I try to avoid them. Try this:

    DELETE tname FROM tname INNER JOIN spam ON (tname.old_id = spam.textid);
    

    Disclaimer: This query is not tested, make backups first! :-)

    0 讨论(0)
  • 2021-01-04 13:18

    Your choice of where id in (select ...) will always perform poorly.

    Instead, use a normal join which will be very efficient:

    DELETE `text` 
    FROM spam
    join `text` on `text`.old_id = spam.textid;
    

    Notice selection from spam first, then joining to text, which will give the best performance.

    0 讨论(0)
提交回复
热议问题