mysql添加外键语句

sql语句格式:

· 添加外键约束:alter table 从表 add constraint 外键(形如:FK_从表_主表) foreign key (从表外键字段) references 主表(主键字段);

注意语句中的(`)全部是Esc下面那个键而非单引号!执行语句时是单引号。
alter table t_book add constraint `fk` foreign key (`bookTypeId`) references t_booktype(`id`);
或者在创表时直接加上

CREATE TABLE t_book(
id int primary key auto_increment,
bookName varchar(20),
author varchar(10),
price decimal(6,2),
bookTypeId int,
constraint `fk` foreign key (`bookTypeId`) references `t_bookType`(`id`)
);

原文地址:https://www.cnblogs.com/xlwh/p/8595141.html