我正在使用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
任何有关这方面的帮助将不胜感激.