【问题标题】:Handling database integrity处理数据库完整性
【发布时间】:2011-06-13 18:59:46
【问题描述】:

我将在我的应用程序的下一个版本中使用 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

对此的任何帮助将不胜感激。

【问题讨论】:

  • @Benj 为什么你的链接指向这个 exact SO 帖子?
  • @BuhakeSindi 好吧...看来我的复制粘贴失败了...谢谢您的指点。很抱歉,我无法(多年后)检索到原始链接。
  • @BuhakeSindi 我建议我们删除所有这些 cmets,因为它们对社区没有用处。
  • 我无法删除其他人的cmets。只有原评论者可以删除他/她的评论。

标签: mysql foreign-keys innodb mysql-error-1093 mysql-error-1452


【解决方案1】:

mySql 的许多怪癖我不是太熟悉,但这应该也可以,也许 mySql 不会被它呛到:

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

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

【讨论】:

  • 谢谢,这对我有用!我已经想出了使用临时表的丑陋解决方案,但是这个很糟糕:) 我会留下一个问题一段时间,这样你就可以得到更多的支持 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 1970-01-01
相关资源
最近更新 更多