运行环境:MySQL5.5
语法:CONSTRAINT fk_name foreign key(column_name) references table_name(column_name)
- 在创建表时直接创建
drop table if exists pay;
drop table if exists employee;
create table employee(id int not null auto_increment, name varchar(20) not null, primary key(id)) engine=InnoDB default charset=UTF8;
create table pay(id int not null auto_increment, emp_id int not null, pay float(7,2) not null, primary key(id), constraint fk_pay_empid foreign key(emp_id) references employee(id)) engine=InnoDB default charset=UTF8;
- 创建表后再添加
drop table if exists pay;
drop table if exists employee;
create table employee(id int not null auto_increment, name varchar(20) not null, primary key(id)) engine=InnoDB default charset=UTF8;
create table pay(id int not null auto_increment, emp_id int not null, pay float(7,2) not null, primary key(id)) engine=InnoDB default charset=UTF8;
alter table pay add constraint fk_pay_empid foreign key (emp_id) references employee(id);
注意事项:
- 表类型必须为InnoDB,外键才有效(高版本MySQL定义表类型使用engine=InnoDB,低版本使用type=InnoDB);
- 使用外键的表只能添加提供外键表存在的记录(employee如果存在id为1的记录,则pay表可以插入emp_id为1的记录);