'MySQL consecutive INSERT statements syntax error
I have a 2 INSERT statements:
INSERT INTO Class (class_name, teacher_id) VALUES ('Math 7A', 000001);
INSERT INTO Class_Student(class_id, student_id) VALUES (1, 000004);
When I inputted each statement one by one, there was no syntax error. But if I put 2 statements together, it returns a syntax error.
You have an error in your SQL syntax; it seems the error is around: 'INSERT INTO Class_Student(class_id, student_id) VALUES (1, 000004)' at line 5
What is in the middle of these 2 statements that causes the syntax error?
PS: Here are my related tables:
-- `User` Table
CREATE TABLE `User` (
user_id int(6) unsigned zerofill NOT NULL AUTO_INCREMENT,
username varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
email varchar(255) NOT NULL,
first_name varchar(255) NOT NULL,
last_name varchar(255) NOT NULL,
is_teacher boolean NOT NULL,
PRIMARY KEY (user_id)
) ENGINE=InnoDB;
-- `Class` Tables
CREATE TABLE Class (
class_id int NOT NULL AUTO_INCREMENT,
class_name varchar(20) NOT NULL,
teacher_id int(6) unsigned NOT NULL,
PRIMARY KEY (class_id),
FOREIGN KEY (teacher_id) REFERENCES `User`(user_id)
) ENGINE=InnoDB;
CREATE TABLE Class_Student (
class_id int NOT NULL,
student_id int(6) unsigned NOT NULL,
PRIMARY KEY (class_id, student_id),
FOREIGN KEY (class_id) REFERENCES Class(class_id),
FOREIGN KEY (student_id) REFERENCES User(user_id)
) ENGINE=InnoDB;
Solution 1:[1]
You can't just make an Insert when you have FOREIGN KEY (teacher_id) REFERENCES User(user_id); You have to have teacher_id before to use it as foreign key in User table.
So you are trying to add a row to your Class table for which no matching row (teacher_id) is present in User table.
I've created your tables and tried to make a query. So I've got another error. So your problem is not syntax error.

Here your problem: Can't insert values into table, foreign key constraint keeps failing
Also here error number I've received from testing your queries: ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
