mysql - 处理数据库完整性

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

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

如有任何帮助,我们将不胜感激。

最佳答案

我不太熟悉 mySql 的许多怪癖,但这应该也可以,也许 mySql 不会因此而窒息:

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

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

关于mysql - 处理数据库完整性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4770035/

相关文章:

mysql - 将最新数据插入mySQL

java - 我使用 LIKE 语句并得到 java.sql.SQLException : After end of result set in mysql

mysql - 违反完整性约束 : 1452 Cannot add or update a child row: a foreign key constraint fails

php - 用户间信用转移的Mysql事务

mysql - 错误 1005 (HY000) : Can't create table 'shrewd_db.alert_disable_register' (errno: 150)

mysql - MySQL 中的匹配集

php - 在 Doctrine2 上有条件地连接表

sql - SQLite 3中空表的奇怪外键行为

sql-server - 为什么这个 T-SQL OUTPUT INTO with FOREIGN KEY hack 有效?

MySQL:特定引用的问题