1

我是数据库新手,在尝试创建这些表时不断收到错误消息。哪里有错?

我发现了很多与我类似的问题,但它们并没有帮助我解决这个问题。

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 STATUS。

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.
4

2 回答 2

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)
);
于 2013-06-03T19:39:38.350 回答
0

您仅引用组合主键的一个字段!

于 2013-06-03T19:39:42.363 回答