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?
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With