0

此插入在我的数据库上失败-

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,
4

1 回答 1

2

您在tig_pairs引用该tig_nodes表的表上有一个外部约束。但是,您没有将任何数据插入到 tisnid字段中。引用的字段 ,tig_nodes.nid不允许 NULL 值。由于这两个限制,您不能将 null 插入nid.tig_pairs

另请参阅此问题:MySQL 外键允许 NULL?

编辑:此外,主键值永远不允许为 NULL;因此,只要nid包含在该主键中,就不能将其设为 NULL。

于 2012-06-15T14:36:49.707 回答