2015-04-06 165 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`)) 

所以请确保您在所有表正确的入口。

希望它有帮助!