Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DELETE using LEFT JOIN with LIMIT in MySQL

I'm trying to delete orphan posts in my database and I have created this query:

DELETE post.*
      FROM foro_post AS post
      LEFT JOIN foro_thread AS thread USING(threadid)
      WHERE thread.threadid IS NULL

The problem is that I want to limit because my table has over 7,000,000 records.

As I can't use LIMIT with the query, I tried this and actually worked, but I'm not sure if is an efficient solution or if it could be done better.

DELETE post.*
      FROM foro_post AS post
      LEFT JOIN foro_thread AS thread USING(threadid)
      WHERE thread.threadid IS NULL
      AND post.postid < 500

      // Where < 500 should be increasing as I delete records

How can I do this more efficiently?

like image 626
Santiago Avatar asked Aug 30 '12 17:08

Santiago


People also ask

Can we use limit in delete query in MySQL?

You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the condition in the WHERE clause. You cannot use ORDER BY or LIMIT in a multiple-table DELETE .

How do you delete using LEFT join?

Delete left join table is used to delete rows from the left table that do not have matching records in the right table. Below is the syntax to of deleting rows with a left join that does not have matching rows in another table: Delete table1 from table1 LEFT JOIN table2 ON table1. col_name=table2.

Can we use LEFT join IN delete query?

We can also use the LEFT JOIN clause in the DELETE statement to delete rows in a table (left table) that does not have matching rows in another table (right table). Note that we only put T1 table after the DELETE keyword, not both T1 and T2 tables like we did with the INNER JOIN clause.


1 Answers

You can't use LIMIT directly within DELETE when you're referencing multiple tables at the same time, but you can get around that by encasing what you want to delete within a subselect:

DELETE po 
FROM   foro_post po
JOIN   (
       SELECT    p.postid
       FROM      foro_post p
       LEFT JOIN foro_thread t ON p.threadid = t.threadid
       WHERE     t.threadid IS NULL
       ORDER BY  p.postid
       LIMIT     50
       ) pp ON po.postid = pp.postid
like image 70
Zane Bien Avatar answered Oct 22 '22 06:10

Zane Bien