mysql - 错误 1005 (HY000) : Can't create table 'db.grades' (errno: 150)

标签 mysql

我在 mysql 中创建了四个表。但是它在创建第 4 个时显示错误。

错误 1005 (HY000):无法创建表“db.grades”(错误号:150)

我检查了外键的名称和类型是否正确。有什么建议么?谢谢。

CREATE TABLE students
(

id int unsigned not null,
first_name VARCHAR(50),
last_name VARCHAR(50),
email_address VARCHAR(50),
primary key (id)

);



-------
CREATE TABLE departments 
(
school_code enum('L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M' ),
dept_id int unsigned,
abbreviation VARCHAR(9),
dept_name VARCHAR(200),
PRIMARY KEY (school_code,dept_id)
);


----

create table courses(
school_code enum('L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M' ),
dept_id int unsigned,
course_code char(5),
name varchar(150),
primary key (school_code,course_code,dept_id)
);


-----

create table grades(
pk_grade_ID int unsigned auto_increment,
student_id int unsigned not null,
grade decimal,
school_code enum('L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M' ),
dept_id int unsigned,
course_code char(5), 
name varchar(150),
primary key (pk_grade_ID),
foreign key (student_id) references students(id),
foreign key (school_code,course_code,name) references courses (school_code,course_code,name)
);

----

最佳答案

Are you sure you're last foreign key in the Grades table should not reference the primary key in the Courses table (which includes dept_id instead of name):

foreign key (school_code,course_code,dept_id)
     references courses (school_code,course_code,dept_id)

这有效 -- http://sqlfiddle.com/#!2/451d1

顺便说一句——如果可能,请考虑完全删除枚举列。相反,创建一个查找表并将其用作外键。

关于mysql - 错误 1005 (HY000) : Can't create table 'db.grades' (errno: 150),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17333506/

相关文章:

mysql - Perl 和 DBI - 加载数组问题

mysql - 跟踪列表数据库

mysql - mysql 上的字符集数据库未更新

php - 使用php抓取html中的表值

php - Ajax不显示mysql数据库的结果

mysql - NHibernate Profiler 不显示查询计划

php - 如何使用 Highcharts 显示数据库中的历史数据和实时数据

java - 数据截断 : Incorrect datetime value: '' for column 'date' at row 1

mysql - B 树中的最小占用率是多少?

c# - 无法使用 c# System.Data.SqlClient 连接到本地数据库