简体   繁体   English

处理数据库完整性

[英]Handling database integrity

I'm introducing database integrity using innodb constraints in the next version of my application. 我正在使用innodb约束在我的应用程序的下一个版本中引入数据库完整性。 Everything goes well, but some of my tables have records with deleted references (dead records) and because of them I can't add constraints to the table. 一切顺利,但我的一些表有记录与删除的引用(死记录),因为他们我不能添加约束到表。

I am trying: 我在尝试:

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

And I get: 我得到:

#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)

Running this query, I found out that over 500 records have no references (authors were deleted, but their articles remained): 运行此查询,我发现超过500条记录没有引用(作者被删除,但他们的文章仍然存在):

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

So, before I can add a constraint, I must deal with those. 所以,在我添加约束之前,我必须处理这些约束。 How do I delete all the records that I get using the query above? 如何删除使用上述查询获得的所有记录?

I've tried: 我试过了:

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

But mysql responds: 但是mysql响应:

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

Any help on this will be greatly appreciated. 任何有关这方面的帮助将不胜感激。

I'm not too familiar with mySql's many quirks, but this should also work, and perhaps mySql won't choke on it: 我不太熟悉mySql的许多怪癖,但是这也应该有用,也许mySql不会阻塞它:

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

Um, of course we always have a backup of the table before we attempt set-based deletes :) 嗯,当然我们在尝试基于集合的删除之前总是有一个表的备份:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM