Mysql

將外鍵設置為空字元串

  • November 19, 2020

我正在嘗試將外鍵設置為空字元串,但我不斷收到此錯誤。

錯誤程式碼:1452。無法添加或更新子行:外鍵約束失敗(msis230.deptchair, CONSTRAINT deptchair_ibfk_1 FOREIGN KEY (PROFESSORID) REFERENCES professor (PROFID))

這是我的程式碼:

INSERT INTO DEPTCHAIR (PROFESSORID, DEPTID)
VALUES ('SJ001', 'MSIS');
INSERT INTO DEPTCHAIR (PROFESSORID, DEPTID)
VALUES ('', 'BIO');
INSERT INTO DEPTCHAIR 
VALUES ('JS001', 'PHY');
INSERT INTO DEPTCHAIR 
VALUES  ('NS001', 'MKT');
INSERT INTO DEPTCHAIR 
VALUES ('', 'ECO');

您可以採取兩種方法

方法#1:添加到教授表

INSERT INTO professor (PROFID) VALUES ('');

然後,所有 INSERT 都DEPTCHAIR將起作用。

方法#2:禁用外鍵檢查

SET foreign_key_checks = 0;
INSERT INTO DEPTCHAIR (PROFESSORID, DEPTID)
VALUES ('', 'BIO');
SET foreign_key_checks = 1;

甚至 ’’ 也是必須存在於父表中的值。

如果您不想將其添加到教授表中,請使用NULLAkina 在評論中已經說過的

INSERT INTO DEPTCHAIR (PROFESSORID, DEPTID)
VALUES ('SJ001', 'MSIS');
INSERT INTO DEPTCHAIR (PROFESSORID, DEPTID)
VALUES (NULL, 'BIO');
INSERT INTO DEPTCHAIR 
VALUES ('JS001', 'PHY');
INSERT INTO DEPTCHAIR 
VALUES  ('NS001', 'MKT');
INSERT INTO DEPTCHAIR 
VALUES (NULL, 'ECO');

引用自:https://dba.stackexchange.com/questions/279921