无法添加或更新子行:尝试添加新行时外键约束失败

问题描述 投票:0回答:1

我当前正在尝试在表中添加新条目。在此表中,我对用户表(用户ID)有一个约束。在某些情况下,还无法设置我的用户ID。如果是空的,我得到一个错误:

Cannot add or update a child row: a foreign key constraint fails

这是我设置约束的方式:

enter image description here

那么有没有一种方法可以将空值插入约束字段?如果没有,那么什么是最好的解决方案,而不是消除约束?

mysql sql phpmyadmin insert
1个回答
0
投票
那么有没有一种方法可以将空值插入约束字段?
是,有。只要由外键控制的列未定义为NOT NULL,就可以在其中插入NULL值,如the manual中所述。不允许插入父表中不存在的非NULL值(其中包括空字符串!)。

MySQL本质上实现了由MATCH SIMPLE定义的语义,该语义允许外键全部或部分为NULL。在这种情况下,允许插入包含此类外键的(子表)行,并且该行与引用的(父)表中的任何行都不匹配。

考虑此

demo on DB Fiddlde

-- parent table create table parent (id int primary key); -- child table create table child ( id int primary key, parent_id int null, -- allow `NULL` values constraint parent_id_fk foreign key(parent_id) references parent(id) ); -- create a parent record insert into parent(id) values(1); -- insert a child record that references the parent: ok insert into child(id, parent_id) values(1, 1); -- insert a child record with a NULL parent_id : ok insert into child(id, parent_id) values(2, NULL); -- insert a child record with a (non-NULL) unknown parent_id insert into child(id, parent_id) values(3, 2); -- Error: Cannot add or update a child row: a foreign key constraint fails

© www.soinside.com 2019 - 2024. All rights reserved.