[英]MySQL error cannot add foreign key constraint
怎么了?
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,您可以參考一列具有唯一索引(未鍵)(見我們能有一個外鍵這是不以任何其他表的主鍵? ),但是這是不規范的行為.
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 ));
將p_code設置為鍵,或者將其設置為唯一鍵或主鍵。
price.p_code
必須是唯一的(需要創建主鍵或唯一鍵)。CREATE TABLE
語句中使用ENGINE = INNODB
。子列的數據類型必須與父列完全匹配。 例如,由於 price.p_code 是一個 char(1),movie.p_code 也需要是一個 char(1),而 price.p_code 需要是一個主鍵或需要創建一個索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.