如何设置外键指向autoincrement int?

时间:2017-02-19 01:48:58

标签: mysql database

我正在尝试设置一个MySQL数据库,其中列是指向另一个自动递增的表的外键。当我尝试使用外键创建表时,出现以下错误:

Can't create table '{DATABASE}' . '{TABLE}' (errorno: 150 "Foreign key constraint is incorrectly formed")

答案found here说问题可能是我试图将普通的int设置为指向autoincrement int的外键。我该如何设置表格结构?

以下是产生错误的声明:

create table test_scores(id INT NOT NULL AUTO_INCREMENT, student_id INT, FOREIGN KEY(id)REFERENCES学生(student_id)ON DELETE CASCADE, test_id INT NOT NULL, FOREIGN KEY(test_id)REFERENCES测试(id)ON DELETE CASCADE, 得分INT NOT NULL, PRIMARY KEY(id));

父表:

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    |                |
+-------+-------------+------+-----+---------+----------------+

1 个答案:

答案 0 :(得分:1)

在这一行:

FOREIGN KEY (id) REFERENCES students(student_id) ON DELETE CASCADE,
你可能打算这样做:

FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,

否则你试图让id外键,这是行不通的,因为在插入记录之前你甚至不知道id是什么。此外,students没有student_id列,因此尝试将其用作外键的关系会失败。