我到處尋找可能的解決方案並且一直未能找到任何東西。錯誤1452(23000):無法添加或更新子行:外鍵約束失敗MySQL
這裏是我的表:
CREATE TABLE IF NOT EXISTS students(
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(40) NOT NULL,
middle_name VARCHAR(20),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
password CHAR(40) NOT NULL,
reg_date DATETIME NOT NULL,
PRIMARY KEY (student_id),
UNIQUE(email));
而且,
CREATE TABLE IF NOT EXISTS subjects(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name VARCHAR(20) NOT NULL,
level_of_entry VARCHAR(12) NOT NULL,
exam_board VARCHAR(12) NOT NULL,
PRIMARY KEY (subject_id),
UNIQUE(subject_id));
最後,
CREATE TABLE IF NOT EXISTS entries (
entry_id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(entry_id),
student_id INT UNSIGNED NOT NULL,
subject_id INT UNSIGNED NOT NULL,
date_of_exam DATETIME NOT NULL,
FOREIGN KEY (student_id) REFERENCES students (student_id),
FOREIGN KEY (subject_id) REFERENCES subjects (subject_id));
我需要輸入5個記錄到使用外鍵與其它表項兩張桌子。這是我用來輸入記錄到的條目代碼:返回
INSERT INTO entries
VALUES (NULL, NULL, NULL, '2010-04-19'),
(NULL, NULL, NULL, '2015-06-17'),
(NULL, NULL, NULL, '2011-07-21'),
(NULL, NULL, NULL, '2009-01-12'),
(NULL, NULL, NULL, '2016-11-16');
此錯誤消息:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`exams`.`entries`, CONSTRAINT `entries_ibfk_1` FOREIGN KEY (`student_id`) REFERENCES `students` (`student_id`))
任何意見或建議,將不勝感激。
當您將字段定義爲NOT NULL時,您如何期望插入null? – e4c5
@ e4c5我不知道還有什麼要放 – Kez
你連接你的條目表的學生ID和主題ID應該在空位。 – Shadow