2013-04-05 206 views
1

繼承人我的輸入到命令行,你可以看到我試圖以不同的方式添加一個外鍵,並繼續得到相同的錯誤我做錯了什麼?MySQL錯誤'Key Column does not exist in table'

mysql> create table membership(

-> m_no char(3) primary key, 
-> m_fname varchar(15) not null, 
-> m_lname varchar(15) not null, 
-> m_street varchar(30) not null, 
-> m_city varchar(20) not null, 
-> m_st char(2) not null, 
-> m_balance varchar(3)); 

查詢OK,0行的影響(1.06秒)

mysql> create table rental(

-> r_no char(4) primary key, 
-> r_date date not null, 
-> foreign key (m_no) references membership(m_no)); 
ERROR 1072 (42000): Key column 'm_no' doesn't exist in table 

mysql> create table rental(
-> r_no char(4) primary key, 
-> r_date date not null, 
-> foreign key (m_no) references membership); 
ERROR 1072 (42000): Key column 'm_no' doesn't exist in table 

mysql> create table rental(
-> r_no char(4) primary key, 
-> r_date date not null, 
-> foreign key (m_no) references membership) 
-> engine=innodb; 
ERROR 1072 (42000): Key column 'm_no' doesn't exist in table 


mysql> create table rental(

-> r_no char(4) primary key, 
-> r_date date not null, 
-> foreign key (m_no) references membership(m_no)) 
-> engine=innodb; 
ERROR 1072 (42000): Key column 'm_no' doesn't exist in table 

mysql> create table rental(

-> r_no char(4) primary key, 
-> r_date date not null); 

查詢OK,0行的影響(0.22秒)

mysql> alter table rental add foreign key (m_no) references membership(m_no); 

ERROR 1072 (42000): Key column 'm_no' doesn't exist in table 

的MySQL>

回答

1

正是如錯誤消息所述:rental沒有名爲m_no的列。

既可以引用現有列(即FOREIGN KEY (r_no) REFERENCES membership(m_no)),也可以將m_no列添加到rental。我不確定你想要做什麼。

+0

太謝謝你了。我對MySQL很陌生,並沒有意識到你必須在創建列之前創建一個外鍵。我想過聲明外鍵創建了列。 – Daniel 2013-04-05 19:16:21

+0

不,聲明外鍵只會創建約束。你必須自己添加列。 – 2013-04-05 19:17:09

+0

我現在有一個新的問題, '的mysql>創建表的價格( - > P_CODE CHAR(1)NOT NULL, - > p_description VARCHAR(20), - > p_rentfee十進制(2,2)不爲空, - > p_dylatefee decimal(2,2)); 查詢OK,0行的影響(0.18秒) 的MySQL>創建表電影( - > mv_no炭(4)不爲空, - > mv_name VARCHAR(50)不爲空, - > mv_year炭(4)不null, - > mv_cost decimal(2,2)not null, - > mv_genre varchar(15)not null, - > p_code char(1)not null, - >外鍵(p_code)引用price(p_code) ); 錯誤1215(HY000):無法添加外鍵約束 mysql>' – Daniel 2013-04-05 19:27:08

1

你必須改變在rental表的外鍵參考r_no列:

create table rental(
r_no char(4) primary key, 
r_date date not null, 
foreign key (r_no) references membership(m_no)); 

SQL Fiddle with Demo

2

的錯誤說法是清楚的。您的租賃表中沒有名爲'm_no'的列。

這是你所追求的:

Create table rental 
(
    r_no char(4) primary key, 
    r_date date not null, 
    foreign key (r_no) references membership(m_no) 
); 
相關問題