MySQL外键

运行环境: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的记录);

转载于:https://www.cnblogs.com/ivy-tang/archive/2013/02/26/2933548.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值