出了什么问题?
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>
答案 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)
答案 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)
price.p_code
必须是唯一的(需要创建主键或唯一键)。ENGINE = INNODB
语句中使用CREATE TABLE
。答案 5 :(得分:0)
子列的数据类型必须与父列完全匹配。例如,由于price.p_code是char(1),movie.p_code也需要是char(1),price.p_code需要是主键或需要创建索引。