MySQL外键报Cannot add foreign key constraint的问题

网上解决方案很多,但都不是我遇到的情况。下面是我的解决方案:

错误代码:

create table teacher(
tno int,
tname varchar(20) not null,
office varchar(20),
level enum('教授','副教授'),
dept varchar(20)
);

create table course(
cno int primary key,
cname varchar(20) not null,
tno int,
FOREIGN KEY (tno) REFERENCES teacher (tno)
);

​


正确代码(在第2行的int后加primary key):

create table teacher(
tno int primary key,
tname varchar(20) not null,
office varchar(20),
level enum('教授','副教授'),
dept varchar(20)
);

create table course(
cno int primary key,
cname varchar(20) not null,
tno int,
FOREIGN KEY (tno) REFERENCES teacher (tno)
);

总结:外键参考的外表属性应为主码,不然会报错Cannot add foreign key constraint

你可能感兴趣的:(MySQL,MySQL,外键,数据库)