怎么了?
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>
最佳答案
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? ),但这不是-标准行为。
关于MySQL报错无法添加外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15842111/