MySQL:删除没有子节点的父记录

时间:2013-03-22 07:37:54

标签: mysql

如何编写一个删除父表中没有子节点的记录的查询?

我有一个表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 个答案:

答案 0 :(得分:6)

你的尝试明白在这里工作:

 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

答案 1 :(得分:2)

这样做:

DELETE FROM  resume
WHERE version = 0
AND (SELECT COUNT(*) FROM personal_skill x WHERE x.resume_id = id)=0

答案 2 :(得分: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

答案 3 :(得分: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