[英]Unique Constraint on Foreign Key Columns
I'm trying to add a unique constraint
to two foreign keys: 我正在尝试为两个外键添加一个
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);
When creating I don't get any errors, but when I'm trying to insert I get: 创建时我没有收到任何错误,但是当我尝试插入时,我得到:
MYSQL ERROR 367421 (could not save new tag data into Mysql): Error 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (
sqse_001
.tagsinblog
, CONSTRAINTtagsinblog_ibfk_2
FOREIGN KEY (id_word
) REFERENCEStagwords
(id_word
))MySQL错误367421(可能不是新的标签数据保存到MySQL):错误1452(23000):不能添加或更新子行,外键约束失败(
sqse_001
。tagsinblog
,约束tagsinblog_ibfk_2
外键(id_word
)参考tagwords
(id_word
) )
When I'm trying to insert in the same table without the unique constraint I don't have any problems. 当我试图在没有唯一约束的同一个表中插入时,我没有任何问题。
I worked on your problem statement and assumed few things as follow 我处理了你的问题陈述并假设了以下几点
your archive
table may looks like this 您的
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
table may looks like this 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
Now your query for table tagsInBlog
现在您查询表
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;
Alter Query for table tagsInBlog
更改表
tagsInBlog
查询
ALTER TABLE tagsinblog ADD UNIQUE tagBlogConstraint (id_word, id_page);
Following Insert statements works fine 以下Insert语句工作正常
INSERT INTO `test`.`tagsinblog` (`id_tag`, `id_word`, `id_page`)
VALUES (NULL, '1', '1'), (NULL, '1', '2');
assuming you have respective entry in table tagswords
and archive
假设您在表
tagswords
和archive
有相应的条目
But if your try to insert any value as foreign key
which value doesn't exist in tables archive
or tagwords
, then it will throw following error 但是,如果您尝试将任何值作为
foreign key
插入表archive
或tagwords
中不存在的值,则会抛出以下错误
#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`))
So Make sure you have proper entry in all table. 因此,请确保您在所有表格中都有正确的条目。
Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.