2015-04-06 218 views
1

我嘗試添加unique constraint的兩個外鍵:唯一約束外鍵列

CREATE TABLE tagsInBlog(
    id_tag int(10) not null auto_increment, 
    id_word int(10) not null, 
    id_page int(11), 
    PRIMARY KEY(id_tag), 
    FOREIGN KEY (id_page) REFERENCES archive(id), 
    FOREIGN KEY (id_word) REFERENCES tagwords(id_word) 
)ENGINE=INNODB DEFAULT CHARSET=utf8; 

ALTER TABLE tagsinblog 
    ADD UNIQUE tagBlogConstraint (id_word, id_page); 

當創建我得不到任何錯誤,但是當我試圖插入我得到:

MySQL錯誤367421(可能不是新的標籤數據保存到MySQL):錯誤 1452(23000):不能添加或更新子行:外鍵 約束失敗(sqse_001tagsinblog,約束 tagsinblog_ibfk_2外鍵(id_word)參考文獻tagwordsid_word))

當我試圖在同一個表中插入沒有唯一約束,我沒有任何問題。

回答

2

我曾在你的問題陳述和假設幾件事情如下

archive表可能看起來像這樣

CREATE TABLE IF NOT EXISTS `archive` (`id` int(11) NOT NULL AUTO_INCREMENT, 
`descrp` varchar(10) NOT NULL DEFAULT '', PRIMARY KEY (id)) ENGINE=InnoDB 

tagwords表可能看起來像這樣

CREATE TABLE IF NOT EXISTS `tagwords` (`id_word` int(11) NOT NULL 
AUTO_INCREMENT, `descrp` varchar(10) NOT NULL DEFAULT '', 
PRIMARY KEY (id_word)) ENGINE=InnoDB 

現在查詢表tagsInBlog

CREATE TABLE tagsInBlog(
id_tag int(10) not null auto_increment, 
id_word int(10) not null, 
id_page int(11), 
PRIMARY KEY(id_tag), 
FOREIGN KEY (id_page) REFERENCES archive(id), 
FOREIGN KEY (id_word) REFERENCES tagwords(id_word) 
)ENGINE=INNODB DEFAULT CHARSET=utf8; 

變更查詢的表tagsInBlog

ALTER TABLE tagsinblog ADD UNIQUE tagBlogConstraint (id_word, id_page); 

以下INSERT語句工作正常

INSERT INTO `test`.`tagsinblog` (`id_tag`, `id_word`, `id_page`) 
VALUES (NULL, '1', '1'), (NULL, '1', '2'); 

假設你在表tagswordsarchive

相應的條目,但如果你嘗試插入任何值爲foreign key哪些值不存在於表archivetagwords,那麼它會拋出以下錯誤

#1452 - Cannot add or update a child row: a foreign key constraint fails 
(`test`.`tagsinblog`, CONSTRAINT `tagsinblog_ibfk_2` 
FOREIGN KEY (`id_word`) REFERENCES `tagwords` (`id_word`)) 

所以請確保您在所有表正確的入口。

希望它有幫助!