1

这是我在命令行中的输入,您可以看到我尝试以不同的方式添加外键并不断收到相同的错误我做错了什么?

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));

查询正常,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);

查询正常,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>

4

3 回答 3

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)
);
于 2013-04-05T19:13:40.267 回答
1

正如错误消息所述:rental没有名为m_no.

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

于 2013-04-05T19:12:23.057 回答
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

于 2013-04-05T19:12:44.690 回答