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 
     ) 

嗯,當然,我們總是有表的備份在我們嘗試基於集的刪除之前:)