2012-12-07 119 views
1

定位我的错误,我不知道我在做什么错在这里,但我得到一个错误:请帮助我在这个MySQL代码

Error Code: 1005. Can't create table 'erm.section' (emo:150) 

这里是代码。 “课程”表已成功创建。我尝试修改'section'表中的course_number attritube的名称,但那不起作用。

USE erm; 

    CREATE TABLE course 
    (
     course_name   VARCHAR(30)  NOT NULL, 
     course_number  VARCHAR(20)  NOT NULL, 
     credit_hours  INT    NOT NULL, 
     department   VARCHAR(10), 
     CONSTRAINT course_pk PRIMARY KEY (course_name) 
    ); 

    CREATE TABLE section 
    (
     section_identifier  INT     NOT NULL, 
     course_number   VARCHAR(20), 
     semester    VARCHAR(10)   NOT NULL, 
     school_year    VARCHAR(4)   NOT NULL, 
     instructor    VARCHAR(25), 
     CONSTRAINT section_pk PRIMARY KEY (section_identifier), 
     CONSTRAINT section_fk FOREIGN KEY (course_number) 
      REFERENCES course (course_number) 
      ON DELETE  SET NULL 
      ON UPDATE  CASCADE 
    ); 

回答

1

course_number不是表中的主键。

表中的外键必须引用另一个表的主键。

1

你必须创建由外键引用的列的索引:

alter table course add index (course_number); 

(这并不一定是一个主键索引)。从MySQL documentation

InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

0
A FOREIGN KEY in one table points to a PRIMARY KEY in another table. 

AFAIK,丢掉CONSTRAINT,然后重命名,然后加回CONSTRAINT是唯一的办法。先备份!

砸使用

ALTER TABLE section 
    DROP FOREIGN KEY course_number 

,并再次添加使用此

ALTER TABLE section 
ADD FOREIGN KEY (course_number) 
REFERENCES course (course_number)