从子查询中删除多行的sql语法错误

ifmq2ha2  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(310)

我有一个使用innodb的关系mysql数据库,它连接课程和课程参加者。这个数据库的问题是 course_id 中的列 course_attendees 未设置为外键。有很多课程都缺了 course_attendees 表正试图引用。
我想删除那些记录,因为这些课程已经不属于我了。我编写了这个选择查询,它选择了所有应该删除的课程:

SELECT
    ca.`id`
  FROM `course_attendees` AS ca
    LEFT JOIN `courses` c
      ON ca.`course_id` = c.`id`
  WHERE c.`id` IS NULL

现在,当我尝试使用如下子查询将其 Package 到delete查询中时:

DELETE FROM courses AS C1
WHERE C1.`id` IN (
  SELECT
    ca.`id`
  FROM `course_attendees` AS ca
    LEFT JOIN `courses` c
      ON ca.`course_id` = c.`id`
  WHERE c.`id` IS NULL
);

我得到以下错误:

[2018-08-30 08:34:26] [42000][1064] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS C1

[2018-08-30 08:34:26] [42000][1064] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS C1
[2018-08-30 08:34:26] WHERE C1.`id` IN (
[2018-08-30 08:34:26] SELECT
[2018-08-30 08:34:26] ca.`id`
[2018-08-30 08:34:26] FROM `course_attendees` AS c' at line 1

既然select查询可以工作,那么这里的问题是什么?如何解决它?
编辑
蒂姆的回答让我犯了一个错误:

[HY000][1093] You can't specify target table 'courses' for update in FROM clause
tpgth1q7

tpgth1q71#

您的外部删除查询与子查询根本不相关,因此您在逻辑上不需要别名:

DELETE
FROM courses
WHERE id IN (
    SELECT id FROM
    (
        SELECT ca.id
        FROM course_attendees AS ca
        LEFT JOIN courses c
            ON ca.course_id = c.id
        WHERE c.id IS NULL
    ) t
);

我不确定delete语句中是否只允许在一个表上使用别名。它们允许删除联接,但您不能这样做。

相关问题