欢迎进入linux社区论坛,与200万技术人员互动交流 >>进入 在更新数据库时使用外键约束 第一个表存储一些简单博客数据,而第二个表则存放这些博客的有关评论。这例子的巧妙之处在于,它给子表定义了一个外键约束,从而允许我们在博客文章被删除时自动地删除有
欢迎进入linux社区论坛,与200万技术人员互动交流 >>进入
在更新数据库时使用外键约束
第一个表存储一些简单博客数据,而第二个表则存放这些博客的有关评论。这例子的巧妙之处在于,它给子表定义了一个外键约束,从而允许我们在博客文章被删除时自动地删除有关的所有评论。下面给出这两个表的定义,它们建立了一个一对多的关系:
01
drop table if exists `test`.`blogs`;
02
03
create table `test`.`blogs` (
04
05
`id` int ( 10 ) unsigned auto_increment,
06
07
`title` text ,
08
09
`content` text ,
10
11
`author` varchar ( 45 ) default null ,
12
13
primary key (`id`)
14
15
) engine = innodb default charset = utf8;
16
17
18
19
drop table if exists `test`.`comments`;
20
21
create table `test`.`comments` (
22
23
`id` int ( 10 ) unsigned auto_increment,
24
25
`blog_id` int ( 10 ) unsigned default null ,
26
27
`comment` text ,
28
29
`author` varchar ( 45 ) default null ,
30
31
primary key (`id`),
32
33
key `blog_ind` (`blog_id`),
34
35
constraint `comments_ibfk_1` foreign key (`blog_id`) references `blogs` (`id`) on update cascade
36
37
) engine = innodb default charset = utf8;
除了给以上两个innodb表定义一些简单字段外,上述的代码还使用了一个外键约束,使得每当父表的“id”键更新时,表comments的相应内容也会级联更新。给父字段“id”定义约束的代码如下所示:
1
constraint `comments_ibfk_1` foreign key (`blog_id`) references `blogs` (`id`) on update cascade
innodb引擎除了可以规定根据父表完成的操作对子表进行的级联更新以外,还可以执行其他的操作,包括“no action”和“restrict”,这样即使父表发生更新或者删除操作,也不会引起对子表的任何操作。
现在,根据上面的mysql表的定义,填充如下所示的数据:
1
insert into blogs (id, title, content, author) values ( null , ' title of the first blog entry ' , ' content of the first blog entry ' , ' tom ' )
2
3
insert into comments (id, blog_id, comment, author) values ( null , 1 , ' commenting first blog entry ' , ' susan norton ' ), ( null , 1 , ' commenting first blog entry ' , ' rose ' )
然后,由于某种原因,我们更新了第一个博客数据,那么只要运行下列sql语句,与该博客文章有关的所有评论也会随之自动更新:
update blogs set id = 2 , title = ' title of the first blog entry ' , content = ' content of the first blog entry ' , author = ' john doe ' where id = 1
这看起来非常不错,对吧?前面讲过,外键约束容许您将表之间的关系的维护工作委托给数据库层,这意味着编写与数据层交互的应用程序时可以省去不少的代码。
[1] [2] [3]