目的:
使两张表产生关联,同步更新内容。
创建员工信息表,创建员工薪资表。观察同步效应
创建父表
父表company.employees
mysql> create table employees(
name varchar(50) not null,
mail varchar(20),
primary key(name)
)engine=innodb;
( primary key(name) )
创建子表
子表company.payroll
mysql> create table payroll(
id int not null auto_increment,
name varchar(50) not null,
payroll float(10,2) not null,
primary key(id),
foreign key(name) references employees(name) on update cascade on delete cascade
)engine=innodb;
( 子表name外键,关联父表(employees 主键name),同步更新,同步删除)
查看表结构
> desc employees;
> desc payroll;
![如图1](https://upload-images.jianshu.io/upload_images/15572377-9f6df47d38b02a75.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
4输入测试数据
insert into employees values ('zhangsan','zhangsan@126.com');
insert into payroll values (1,'zhangsan',20000.23);
select * from employees;
select * from payroll;
插入数据
父表更新,子表会如何
update employees set name='zhangsansss' where name='zhangsan';
select * from payroll;
父表删除,子表会如何
delete from employees where name='zhangsansss';
总结
当父表中某个员工的记录修改时,子表也会同步修改
当父表中删除某个记录,子表也会同步删除该记录。