MySQL,MariaDB:无法创建表 - ERROR 1005(HY000)。外键有问题

时间:2013-06-03 19:34:31

标签: mysql mariadb

我是数据库的新手,当我尝试创建这些表时,我不断收到错误。哪里出错?

我发现了很多类似于我的问题,但是他们没有帮助我解决这个问题。

CREATE TABLE IF NOT EXISTS course
(
    cou_id VARCHAR(3),
    course_name VARCHAR(25),
    CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);

CREATE TABLE IF NOT EXISTS students_marks
(
    stu_id INT, 
    student_name VARCHAR(25), 
    course_name VARCHAR(25), 
    first_mark NUMERIC(2,0), 
    second_mark NUMERIC(2,0), 
    third_mark NUMERIC(2,0),
    CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
    CONSTRAINT fk_studentsmarks_course FOREIGN KEY (course_name) REFERENCES course (course_name)
);

这是来自INNODB状态。

LATEST FOREIGN KEY ERROR
------------------------
130603 20:17:22 Error in foreign key constraint of table testdb/students_marks:
 FOREIGN KEY (course_name) REFERENCES course (course_name)
):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.

2 个答案:

答案 0 :(得分:0)

您的主键在课程表中设置为cou_idcourse_name。要在students_marks表中添加外键约束,您必须引用这两个字段(并在表定义中包含这两个字段):

CREATE TABLE IF NOT EXISTS course
(
    cou_id VARCHAR(3),
    course_name VARCHAR(25),
    CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);

CREATE TABLE IF NOT EXISTS students_marks
(
    stu_id INT, 
    student_name VARCHAR(25), 
    cou_id VARCHAR(3),
    course_name VARCHAR(25), 
    first_mark NUMERIC(2,0), 
    second_mark NUMERIC(2,0), 
    third_mark NUMERIC(2,0),
    CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
    CONSTRAINT fk_studentsmarks_course FOREIGN KEY (cou_id,course_name) REFERENCES course(cou_id,course_name)
);

答案 1 :(得分:0)

您只引用复合主键的一个字段!