2012-12-07 117 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)