删除孤儿记录 - mysql

时间:2014-08-14 07:33:14

标签: php mysql sql join laravel

我有以下表格

question
-------------------
id | name

quiz_results
------------------
id|question_id|is_correct

无意中我从后端删除了一些问题 注意:我使用了laravel框架并使用了模型来维护依赖性。我没有在数据库级别上使用任何关系。 现在我需要从quiz_results中删除孤儿记录(即我需要删除那些意外删除了问题的记录)

我在下面试过

delete from quiz_results where id IN (SELECT qr.id
FROM  `quiz_results` qr
LEFT JOIN questions q ON ( q.id = qr.question_id ) 
WHERE q.id IS NULL )

它给出了以下错误

1093 - 您无法在FROM子句

中为更新指定目标表'quiz_results'

之前我也试过没有子查询,如下面的

delete from
FROM  `quiz_results` qr
LEFT JOIN questions q ON ( q.id = qr.question_id ) 
WHERE q.id IS NULL

抛出语法错误

#1064 - 您的SQL语法出错;查看与MySQL服务器版本对应的手册,以便在“FROM quiz_results qr LEFT JOIN问题附近使用正确的语法q ON(q.id = qr.question_id)WH'在第2行

3 个答案:

答案 0 :(得分:3)

尝试以下查询:
DELETE FROM quiz_results WHERE question_id NOT IN(SELECT id FROM question)

答案 1 :(得分:1)

试试这个

delete from quiz_results r 
where not exists 
    (
        select 1 
        from question q 
        where q.id=r.question_id
    )

答案 2 :(得分:0)

delete from FROM `quiz_results`

->

delete `quiz_results` FROM  `quiz_results`