主键和外键冲突

时间:2012-06-15 14:25:49

标签: mysql foreign-keys primary-key constraints

这个插入在我的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`))

表定义是:

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;

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;

省略了行PRIMARY KEY (nid, pkey), -- ***,然后我的查询就完成了。主键和令人不安的外键约束之间是否存在冲突?我怎么能避免呢?主键必须留在那里:)

谢谢!

编辑:通过在一行上更改tig_pairs定义来消除错误:

nid int unsigned NOT NULL auto_increment,

1 个答案:

答案 0 :(得分:2)

您的tig_pairs表引用tig_nodes表有外来约束。但是,您没有在tis nid字段中插入任​​何数据。引用的字段tig_nodes.nid不允许NULL值。由于这两个约束,您无法将null插入nid的{​​{1}}字段。

另请参阅此问题:MySQL foreign key to allow NULL?

编辑:同样,主键值永远不允许为NULL;因此,只要该主键中包含tig_pairs,就不能使其为NULL。