2012-04-09 174 views
2

如果我在InnoDB引擎上設計數據庫,並且我有3個表,我無法刪除,因爲每個表示「外鍵約束失敗」 - 是否意味着設計錯誤?圓形外鍵約束失敗mysql

請參閱下面的結構:

CREATE TABLE IF NOT EXISTS `account` (
    `account_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, 
    PRIMARY KEY (`account_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; 


CREATE TABLE IF NOT EXISTS `identity` (
    `identity_id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `user_id` int(10) unsigned DEFAULT NULL, 
    `account_id` smallint(5) unsigned DEFAULT NULL, 
    PRIMARY KEY (`identity_id`), 
    KEY `fk_details1` (`user_id`), 
    KEY `fk_account1` (`account_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; 


CREATE TABLE IF NOT EXISTS `user` (
    `user_id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `login` varchar(64) NOT NULL DEFAULT '', 
    `password` varchar(32) NOT NULL DEFAULT '', 
    `default_identity_id` int(10) unsigned DEFAULT NULL, 
    PRIMARY KEY (`user_id`), 
    UNIQUE KEY `login_UNIQUE` (`login`), 
    KEY `fk_identity1` (`default_identity_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; 

-- 
-- Constraints for table `identity` 
-- 
ALTER TABLE `identity` 
    ADD CONSTRAINT `fk_details1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE, 
    ADD CONSTRAINT `fk_account1` FOREIGN KEY (`account_id`) REFERENCES `account` (`account_id`) ON DELETE CASCADE ON UPDATE CASCADE; 

-- 
-- Constraints for table `user` 
-- 
ALTER TABLE `user` 
    ADD CONSTRAINT `fk_identity1` FOREIGN KEY (`default_identity_id`) REFERENCES `identity` (`identity_id`) ON DELETE CASCADE ON UPDATE CASCADE; 

我懷疑問題是default_identity_id ...我將它作爲一個標誌,標識表?

請指教!

+2

循環引用很難處理。您可以將'default_identity_id'作爲標誌移動到'identity table',或者您可以添加另一個'default_identity'表。看到類似的問題:[MySQL數據庫設計。插入1to1表中的行](http://stackoverflow.com/questions/6691366/mysql-database-design-inserting-rows-in-1to1-tables/6692054#6692054)(閱讀那些Parent-Child-BestChild作爲User- Identity-DefaultIdentity) – 2012-04-09 10:57:15

+1

非常好。而已。請讓它成爲答案,以便我可以接受它:)。 – RandomWhiteTrash 2012-04-09 11:00:46

+0

我的MySQL 5.5.15.0似乎是'刪除循環相關的數據就好了。您能否發佈重現問題的測試數據? – 2012-04-10 06:32:43

回答