了解MySQL中的外键作用

发布时间:2024-05-05 点击:110
【相关学习推荐:mysql学习】
mysql外键的作用:
保持数据一致性,完整性,主要目的是控制存储在外键表中的数据。使两张表形成关联,外键只能引用外表中列的值!
我们来建两个表
create table `example1` ( `stu_id` int(11) not null default '0', `course_id` int(11) not null default '0', `grade` float default null, primary key (`stu_id`,`course_id`));create table `example2` ( `id` int(11) not null, `stu_id` int(11) default null, `course_id` int(11) default null, primary key (`id`), key `f_ck` (`stu_id`,`course_id`), constraint `f_ck` foreign key (`stu_id`, `course_id`) references `example1` (`stu_id`, `course_id`));insert into example1 (stu_id,course_id,grade)values(1,1,98.5),(2,2,89);insert into example2 (id,stu_id,course_id)values(1,1,1),(2,2,2);我们建了
example1表,里面包含stu_id学号,course_id课程号,grade分数
example2表,里面包含id,stu_id学号,course_id课程号,然后建立外键
分别插入数据到两个表中。
我们把example2中的stu_id和course_id称为example2表的外键,example1是父表,example2是字表,两个表形成关联,必须字表的数据删除后,才能删除父表中的对应数据
现在我们来删除example1中的一条数据
delete from example1 where stu_id=2;会发现报错
error 1451 (23000): cannot delete or update a parent row: a foreign key constraint fails (`test`.`example3`, constraint `f_ck` foreign key (`stu_id`, `course_id`) references `example2` (`stu_id`, `course_id`))
因为example2中的数据关联了example1的数据,这样是删不了的,达到了外键的作用;
然后我们来先删除example2表中的数据,再删除example1表中的数据
delete from example2 where stu_id=2;
delete from example1 where stu_id=2;
这样就成功了;
事件触发限制:
on delete和on update , 可设参数cascade(跟随外键改动), restrict(限制外表中的外键改动),set null(设空值),set default(设默认值),[默认]no action
我们来看看事件触发限制是干嘛的。。。
我们先删除外键,然后重新建立外键带上事件触发限制
alter table example2 drop foreign key f_ck; alter table example2 add constraint `f_ck` foreign key (`stu_id`, `course_id`) references `example1` (`stu_id`, `course_id`) on delete cascade on update cascade;
我们先查看一下数据
mysql> select * from example1;select * from example2;
-------- ----------- ------- | stu_id | course_id | grade | -------- ----------- ------- | 1 | 1 | 98.5 | -------- ----------- ------- 1 row in set (0.00 sec) ---- -------- ----------- | id | stu_id | course_id | ---- -------- ----------- | 1 | 1 | 1 | ---- -------- ----------- 1 row in set (0.00 sec)这时example1和example2中的stu_id和course_id都是1,
再来修改example1表中的数据看看
update example1 set stu_id=3,course_id=3 where stu_id=1;
再来查看数据
mysql> select * from example1;select * from example2;
-------- ----------- ------- | stu_id | course_id | grade | -------- ----------- ------- | 3 | 3 | 98.5 | -------- ----------- ------- 1 row in set (0.00 sec) ---- -------- ----------- | id | stu_id | course_id | ---- -------- ----------- | 1 | 3 | 3 | ---- -------- ----------- 1 row in set (0.00 sec)发现没,example1和example2中的stu_id和course_id都变成了3
我们在来删除example1表中的数据
delete from example1 where stu_id=3;
会发现可以删除,而且example2中的数据也没有了;
其实啊,外键就这个作用,保持数据一致性,完整性,是不让改还是一起改,由事件触发器决定;
相关学习推荐:编程视频

根据域名查询ip地址的方法有哪些 域名能用来干什么
php怎样开启错误提示
服务好的嘉兴网站建设公司推荐
云服务器配置如何打包
com后缀域名和cn后缀域名有什么区别?com后缀域名有什么优势?
如何注册域名网站 注册域名以后怎么使用
建设网站要知道的关键因素
免费自助建站哪个好?新手该怎么选择呢?