[英]primary keys and foreign keys conflict
this insert fails on my db - 这个插入在我的db上失败了 -
insert into tig_pairs (pkey, pval, uid) select 'schema-version', '4.0', uid from tig_users where (sha1_user_id = sha1(lower('db-properties')));
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`tigasedb`.`tig_pairs`, CONSTRAINT `tig_pairs_constr_2` FOREIGN KEY (`nid`) REFERENCES `tig_nodes` (`nid`))
Where table definitions are: 表定义是:
create table if not exists tig_pairs (
nid int unsigned,
uid int unsigned NOT NULL,
pkey varchar(255) NOT NULL,
pval mediumtext,
PRIMARY KEY (nid, pkey), -- ***
key pkey (pkey),
key uid (uid),
key nid (nid),
constraint tig_pairs_constr_1 foreign key (uid) references tig_users (uid),
constraint tig_pairs_constr_2 foreign key (nid) references tig_nodes (nid)
)
ENGINE=InnoDB default character set utf8 ROW_FORMAT=DYNAMIC;
and 和
create table if not exists tig_nodes (
nid int unsigned NOT NULL auto_increment,
parent_nid int unsigned,
uid int unsigned NOT NULL,
node varchar(255) NOT NULL,
primary key (nid),
unique key tnode (parent_nid, uid, node),
key node (node),
key uid (uid),
key parent_nid (parent_nid),
constraint tig_nodes_constr foreign key (uid) references tig_users (uid)
)
ENGINE=InnoDB default character set utf8 ROW_FORMAT=DYNAMIC;
The line PRIMARY KEY (nid, pkey), -- ***
gets omitted, then my query goes through just fine. 行PRIMARY KEY (nid, pkey), -- ***
被省略,然后我的查询通过就好了。 Is there a conflict between that primary key and the troubling foreign key constraint ? 主键和令人不安的外键约束之间是否存在冲突? How can I avoid it ? 我怎么能避免呢? The primary key has to stay there :) 主键必须留在那里:)
Thanks! 谢谢!
EDIT: got rid of the error by changing the tig_pairs definition on one line: 编辑:通过更改一行上的tig_pairs定义来摆脱错误:
nid int unsigned NOT NULL auto_increment,
You have a foreign constraint on your tig_pairs
table referencing the tig_nodes
table. 您的tig_pairs
表引用了tig_nodes
表的外部约束。 However, you are not inserting any data into tis nid
field. 但是,您没有在tis nid
字段中插入任何数据。 The referenced field, tig_nodes.nid
, doesn't allow NULL values. 引用的字段tig_nodes.nid
不允许NULL值。 Due to these two constraints, you cannot INSERT null into the nid
field of tig_pairs
. 由于这两个约束,您不能将null INSERT到tig_pairs
的nid
字段中。
See also this question: MySQL foreign key to allow NULL? 另见这个问题: MySQL外键允许NULL吗?
Edit: also, primary key values are never allowed to be NULL; 编辑:同样,主键值永远不允许为NULL; so as long as nid
is included in that primary key, you cannot make it NULL. 因此只要nid
包含在该主键中,就不能使其为NULL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.