MySQL错误'关键列不存在于表'

时间:2013-04-05 19:10:07

标签: mysql

继续我对命令行的输入你可以看到我试图以不同的方式添加一个外键并继续得到同样的错误我做错了什么?

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>

3 个答案:

答案 0 :(得分: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)
);

答案 1 :(得分:1)

正如错误消息所述:rental没有名为m_no的列。

引用现有列(即FOREIGN KEY (r_no) REFERENCES membership(m_no)),或将m_no列添加到rental。我不确定你要做什么。

答案 2 :(得分:1)

您必须更改r_no表中rental列的外键引用:

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