2011-01-22 128 views
7

我在下一个版本的应用程序中使用innodb约束来介绍数据库完整性。一切顺利,但我的一些表中有删除引用记录(死记录),因为他们我不能添加约束表。处理数据库完整性

我想:

ALTER TABLE `article` ADD FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE; 

我也得到:

#1452 - Cannot add or update a child row: a foreign key constraint fails (`books`.<result 2 when explaining filename '#sql-442_dc'>, CONSTRAINT `#sql-442_dc_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE) 

运行此查询,我发现了超过500个记录没有引用(作者被删除,但他们的文章依然) :

SELECT `articles`.`id` 
FROM `articles` LEFT JOIN `authors` ON `articles`.`author_id` = `authors`.`id` 
WHERE ISNULL(`authors`.`id`); 

因此,在添加约束之前,我必须处理这些约束。 如何删除使用上述查询获得的所有记录?

我已经试过:

DELETE FROM `articles` WHERE `id` IN (
    SELECT `articles`.`id` 
    FROM `articles` LEFT JOIN `authors` ON `articles`.`author_id` = `authors`.`id` 
    WHERE ISNULL(`authors`.`id`); 
) 

但MySQL的回应:

You can't specify target table 'articles' for update in FROM clause 

任何帮助在此将不胜感激。

+0

请参阅:http://stackoverflow.com/questions/4770035/handling-database-integrity(重复) – Benj 2013-04-16 10:30:10

+0

@Benj为什么你的链接指向此**完全** SO帖子? – 2015-10-16 13:22:00

回答

14

我不是太熟悉MySQL的许多怪癖,但这也应该工作,也许MySQL不会在它呛:

delete from articles 
where not exists (
      select id from authors 
      where authors.id = articles.author_id 
     ) 

嗯,当然,我们总是有表的备份在我们尝试基于集的删除之前:)