MySQL错误无法添加外键约束

时间:2013-04-05 19:36:21

标签: mysql

出了什么问题?

mysql> create table price(
    -> p_code char(1) not null,
    -> p_description varchar(20),
    -> p_rentfee decimal(2,2) not null,
    -> p_dylatefee decimal(2,2));
Query OK, 0 rows affected (0.18 sec)

mysql> create table movie(
    -> mv_no char(4) not null,
    -> mv_name varchar(50) not null,
    -> mv_year char(4) not null,
    -> mv_cost decimal(2,2) not null,
    -> mv_genre varchar(15) not null,
    -> p_code char(1) not null,
    -> foreign key (p_code) references price(p_code));
ERROR 1215 (HY000): Cannot add foreign key constraint

mysql>

6 个答案:

答案 0 :(得分:7)

price.p_code不是price的主键。尝试:

create table price(
p_code char(1) not null PRIMARY KEY,
p_description varchar(20),
p_rentfee decimal(2,2) not null,
p_dylatefee decimal(2,2));

通常,外键必须引用主/唯一密钥,完整的主/唯一密钥,以及主/唯一密钥。

在某些RDBMS中,例如SQL Server,可以引用具有唯一索引(不是键)的列(请参阅can we have a foreign key which is not a primary key in any other table?),但这样是非标准行为。

答案 1 :(得分:4)

  • 引擎应该是相同的,例如。 InnoDB的
  • 数据类型应该相同,且长度相同。 e.g。 VARCHAR(20)
  • 归类列charset应该是相同的。 e.g。 UTF8
    警告:即使您的表具有相同的排序规则,列仍然可以有不同的列。
  • 唯一 - 外键应引用参考表中唯一的字段(通常是私钥)。

答案 2 :(得分:2)

p_code应该是price表中的主键:

create table price(
-> p_code char(1) not null,
-> p_description varchar(20),
-> p_rentfee decimal(2,2) not null,
-> p_dylatefee decimal(2,2),
-> PRIMARY KEY ( p_code ));

答案 3 :(得分:0)

p_code 设置为关键,将其设置为唯一键主键

答案 4 :(得分:0)

  1. 引用的列price.p_code必须是唯一的(需要创建主键或唯一键)。
  2. 两个表必须是 InnoDb 表,在ENGINE = INNODB语句中使用CREATE TABLE

答案 5 :(得分:0)

子列的数据类型必须与父列完全匹配。例如,由于price.p_code是char(1),movie.p_code也需要是char(1),price.p_code需要是主键或需要创建索引。