I am trying to set up a MySQL database where a column is a foreign key pointing to another table that auto increments. When I try to create the table with the foreign key, I get the following error:
Can't create table '{DATABASE}' . '{TABLE}' (errorno: 150 "Foreign key constraint is incorrectly formed")
An answer found here says that the problem could be that I am trying to set a normal int as a foreign key pointing to an autoincrement int. How should I go about setting up my table structure?
Here is the statement that produces the error:
create table test_scores(id INT NOT NULL AUTO_INCREMENT, student_id INT, FOREIGN KEY (id) REFERENCES students(student_id) ON DELETE CASCADE, test_id INT NOT NULL, FOREIGN KEY (test_id) REFERENCES tests(id) ON DELETE CASCADE, score INT NOT NULL, PRIMARY KEY (id));
Parent tables:
students
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
tests
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+