this insert fails on my 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. 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:
nid int unsigned NOT NULL auto_increment,
You have a foreign constraint on your
tig_pairstable referencing thetig_nodestable. However, you are not inserting any data into tisnidfield. The referenced field,tig_nodes.nid, doesn’t allow NULL values. Due to these two constraints, you cannot INSERT null into thenidfield oftig_pairs.See also this question: MySQL foreign key to allow NULL?
Edit: also, primary key values are never allowed to be NULL; so as long as
nidis included in that primary key, you cannot make it NULL.