创建表 users1
create table users1(
-> id smallint unsigned primary key auto_increment,
-> username varchar(10) not null,
-> pid smallint unsigned,
-> foreign key (pid) references provinces (id)on delete cascade -> );
其中 on delete cascade意思是,当父表中删除/更新了,子表中也立即删除/更新。
在刚才的table provinces中,插入三条记录,并在子table users1插入一条记录:
insert users1(username,pid) values(‘Tom',3);
其中Tom是username,3就是第3个,就是父表中的C。
如果insert users1(username,pid) values(‘David’,6);
无法insert数据,因为父表最大只到3,而插入的数据pid是6.
所以,可以改为:insert users1(username,pid) values(‘Ross',1);
查询users1中的记录:
之前记录未写入成功,但id还是自动+1。
将父表中的id=3删除,是否会影响子表的数据:
delete from provinces where id = 3;
子表中pid=3的记录已经全部被删除。
同样的,还有些其他的外键约束:
1.cascade:若父表删除/更新,则子表相应删除/更新;
2.set null:若父表删除/更新,则子表相应的外键设置为null(相应字段不能是not null);
3.restrict:若父表删除/更新,子表无变化;
4.no action:与restrict一样。
mac终端进入mysql:/usr/local/mysql/bin/mysql
http://www.imooc.com 来自iMooc的教学