如何从多个表中使用NOT IN删除行

时间:2018-04-08 08:24:34

标签: php mysql mysqli

如何在sql中使用多个NOT IN

DELETE FROM courses
    WHERE course_id
        NOT IN
        (SELECT course_id FROM enrollment)
        AND course_id = $id

我试过的一些方法

DELETE FROM courses
    WHERE course_id
        NOT IN
        ((SELECT course_id FROM enrollment) || (SELECT courseid FROM fees))
        AND course_id = $id  

DELETE FROM courses
    WHERE course_id
        NOT IN (SELECT course_id FROM enrollment)
        OR 
        NOT IN (SELECT courseid FROM fees)
        AND course_id = $id

DELETE FROM courses
    WHERE course_id
        NOT IN
        (SELECT course_id FROM enrollment WHERE course_id = $id
        UNION
        SELECT courseid FROM fees WHERE courseid = $id)

1 个答案:

答案 0 :(得分:1)

以下应该可以正常工作:

DELETE FROM courses
WHERE course_id NOT IN (SELECT course_id FROM enrollment)
  AND course_id NOT IN (SELECT courseid FROM fees)
  AND course_id = $id

如果它仍然不适合您,我建议您将 DELETE 更改为 SELECT course_id 并逐个添加/删除条件,直到您了解正在发生的情况为止你的查询。

只要您想在单个查询中使用 OR AND ,建议您使用括号,以便更容易阅读检查条件的顺序。