I have a table carts and cartitems, the second one has a foreign key to the first. Now I want to delete all rows from carts that are older than 3 months and have no related cartitems. The following query gives me the correct result:
SELECT *
FROM `carts` c
LEFT OUTER JOIN `cartitems` i ON ( `c`.`id` = `i`.`cart_id` )
WHERE `c`.`last_updated` < DATE_SUB(NOW() , INTERVAL 3 MONTH)
GROUP BY `c`.`id`
HAVING COUNT( `i`.`id` ) = 0;
But I can’t figure out how to turn this query into a DELETE.
Also, since there are ~10 million rows in the carts table, I’d be thankful for suggestions on how to improve this query 🙂
You can run the following without
LIMITor with aLIMITto delete the rows in batches.