MySQL错误无法添加外键约束

Dan*_*iel 4 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>
Run Code Online (Sandbox Code Playgroud)

lc.*_*lc. 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));
Run Code Online (Sandbox Code Playgroud)

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

在一些RDBMS,例如SQL Server,您可以引用列,具有独特的索引(未键)(见我们能有一个外键这是不以任何其他表的主键?),但是这是不规范的行为.


am0*_*0wa 7

  • 引擎应该是相同的,例如 InnoDB
  • 数据类型应该相同,并且长度相同。例如 VARCHAR(20)
  • Collat​​ion Columns 字符集应该相同。例如 utf8
    Watchout:即使您的表具有相同的排序规则,列仍然可以具有不同的排序规则。
  • 唯一- 外键应该指的是被引用表中唯一的字段(通常是主键)。