如何使用外键将值插入 table?

How can i insert value into a table with foreign key?

我有 this tables

方案

而且我根本无法将任何值插入第二个或 3d table,因为错误 1452(无法添加或更新子行。) 我怎样才能插入东西? (不使用 SET FOREIGN_KEY_CHECKS=0;)

如果您有循环外键引用,则无法直接插入数据 - 插入任何 table 都因外键违规而失败,并且不支持每个查询插入多个 table .

解决方案:插入第一个 table 但将引用列设置为 NULL,插入第二个 table,首先更新 table。

示例:

CREATE TABLE test1 (t1_id INT PRIMARY KEY, t2_id INT);
CREATE TABLE test2 (t1_id INT, t2_id INT PRIMARY KEY);
ALTER TABLE test1 ADD FOREIGN KEY (t2_id) REFERENCES test2 (t2_id);
ALTER TABLE test2 ADD FOREIGN KEY (t1_id) REFERENCES test1 (t1_id);
INSERT INTO test1 VALUES (1,11);
Cannot add or update a child row: a foreign key constraint fails (`db_262184466`.`test1`, CONSTRAINT `test1_ibfk_1` FOREIGN KEY (`t2_id`) REFERENCES `test2` (`t2_id`))
INSERT INTO test2 VALUES (1,11);
Cannot add or update a child row: a foreign key constraint fails (`db_262184466`.`test2`, CONSTRAINT `test2_ibfk_1` FOREIGN KEY (`t1_id`) REFERENCES `test1` (`t1_id`))
INSERT INTO test1 VALUES (1,NULL);
INSERT INTO test2 VALUES (1,11);
UPDATE test1 SET t2_id = 11 WHERE t1_id = 1;
SELECT * FROM test1; 
SELECT * FROM test2;
t1_id | t2_id
----: | ----:
    1 |    11

t1_id | t2_id
----: | ----:
    1 |    11

db<>fiddle here