删除带有JOIN的选择的结果

时间:2015-05-04 21:48:10

标签: mysql sql join

我有users的表格,可能会或可能没有photos上传。我想删除拥有照片的所有用户。现在我可以让用户没有这样的照片:

SELECT a.id FROM users a
LEFT JOIN images b
ON a.id = b.user_id
WHERE b.user_id is null

但是,我对如何真正实现删除感到有点困惑。

这不起作用:

DELETE FROM users c WHERE c.id IN ( SELECT a.id FROM users a
    LEFT JOIN images b
    ON a.id = b.user_id
    WHERE b.user_id is null
    )

这两点都没有:

DELETE FROM users a
LEFT JOIN images b
ON a.id = b.user_id
WHERE b.user_id is null

对JOIN的结果进行删除的正确方法是什么?

3 个答案:

答案 0 :(得分:0)

DELETE users
WHERE NOT EXISTS (
    SELECT 1
    FROM images i
    WHERE users.user_id = i.user_id)

答案 1 :(得分:0)

我猜你的第二个例子失败了,因为它引用了子查询中的表,但它实际上并不需要:

DELETE FROM users c WHERE c.id NOT IN ( SELECT DISTINCT user_id FROM images);

否则,我会做到这一点:

DELETE FROM users 
USING users AS u LEFT JOIN images AS i ON u.id = i.user_id 
WHERE i.user_id IS NULL;

答案 2 :(得分:0)

你几乎有删除连接查询,但需要提供要删除的表。

试试这个:

delete a.* from users a left join images b on a.user_id=b.user_id where b.user_id is null;