MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

后端 未结 16 1785
误落风尘
误落风尘 2020-11-30 01:37

I have read Database system concepts, 6th edition, Silberschatz. I\'m going to implement the university database system shown in chapter 2 on OS X

相关标签:
16条回答
  • 2020-11-30 02:20

    The syntax of FOREIGN KEY for CREATE TABLE is structured as follows:

    FOREIGN KEY (index_col_name)
            REFERENCES table_name (index_col_name,...)
    

    So your MySQL DDL should be:

     create table course (
            course_id varchar(7),
            title varchar(50),
            dept_name varchar(20),
            credits numeric(2 , 0 ),
            primary key (course_id),
            FOREIGN KEY (dept_name)
                REFERENCES department (dept_name)
        );
    

    Also, in the department table dept_name should be VARCHAR(20)

    More information can be found in the MySQL documentation

    0 讨论(0)
  • 2020-11-30 02:20

    Maybe your dept_name columns have different charsets.

    You could try to alter one or both of them:

    ALTER TABLE department MODIFY dept_name VARCHAR(20) CHARACTER SET utf8;
    ALTER TABLE course MODIFY dept_name VARCHAR(20) CHARACTER SET utf8;
    
    0 讨论(0)
  • 2020-11-30 02:22

    It's worth noting that this error can also happen if the target table or column you're using in the REFERENCES portion simply doesn't exist.

    0 讨论(0)
  • 2020-11-30 02:24

    It is also possible to get this error if the foreign key is not a primary key within its own table.

    I did an ALTER TABLE and accidentally removed the primary key status of a column, and got this error.

    0 讨论(0)
提交回复
热议问题