4

如何编写从不存在子表的父表中删除记录的查询?

我有一个表resume和一个表personal_skill,其中包含一个resume_id引用简历表的字段。我需要删除简历表中没有personal_skill具有此类 resume_id 记录的所有记录。

我试着这样做:

    DELETE
    FROM
      resume
    WHERE
      version = 0
      AND NOT EXISTS (SELECT NULL
                      FROM
                        personal_skill x
                      WHERE
                        x.resume_id = id)

但是这个查询失败了,因为我不能使用我在 SELECT 部分中删除的表。

4

4 回答 4

8

您的尝试在这里显然有效:

 DELETE 
 FROM resume     
 WHERE version = 0
   AND NOT EXISTS (
     SELECT id                       
     FROM personal_skill x
     WHERE x.resume_id = resume.id
  );

如果没有,id那么问题可能很简单(personal_skill 有personal_skill.id专栏吗?)。

另一种选择是:

 DELETE resume  
 FROM resume 
 LEFT JOIN personal_skill 
    ON personal_skill.resume_id=resume.id 
 WHERE personal_skill.id IS NULL; -- or any non-NULLable column from personal_skill
于 2013-03-22T07:50:36.437 回答
2

做这个:

DELETE FROM  resume
WHERE version = 0
AND (SELECT COUNT(*) FROM personal_skill x WHERE x.resume_id = id)=0
于 2013-03-22T07:44:18.773 回答
1

试试这个:

DELETE resume FROM
resume LEFT OUTER JOIN personal_skill
ON resume.resume_id = personal_skill.resume_id
WHERE personal_skill.resume_id IS NULL
于 2013-03-22T07:48:50.000 回答
1

尝试 LEFT JOIN 语法:

DELETE R 
FROM resume R
LEFT JOIN personal_skill PS ON PS.resume_id = R.id
WHERE PS.id IS NULL AND R.version = 0
于 2013-03-22T07:50:15.093 回答