使用子查询进行删除更有效

时间:2011-08-31 16:29:55

标签: mysql

在这里做一些垃圾收集并使用子查询,我知道它不是很有效。有什么指针吗?

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

基本上它应该从我的购物车表中删除会话表中没有相应记录的所有记录。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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;

所以

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