简体   繁体   中英

Make delete with sub-query more efficient

Doing a little garbage collection here and using a subquery, which I know isn't very efficient. Any pointers?

DELETE FROM `carts` WHERE `id` NOT IN (SELECT `cart_id` FROM `sessions`)

Basically it's supposed to delete all records from my carts table that don't have a corresponding record in the sessions table.

DELETE FROM `carts` c 
left outer join `sessions` s on (s.`cart_id` = c.`id`)
WHERE s.`cart_id` is null

http://dev.mysql.com/doc/refman/5.0/en/delete.html

DELETE t1 FROM t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t2.id IS NULL;

So

DELETE carts 
FROM carts 
LEFT JOIN sessions ON carts.id=sessions.cart_id
WHERE session.cart_id is null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM