级联删除

本文通过具体实例展示了如何在SQL中实现级联删除操作,即当删除某个主题时,与其相关的所有帖子也会被一同删除。文章首先创建了两个表:topic和post,并设置外键约束以便在删除topic表中的记录时能够自动删除post表中对应的记录。
根据topic表的id   
把topic表的该id记录删掉  同时删掉post表的相应topic_id的记录

SQL> drop table topic;

表已丢弃。

SQL> drop table post;

表已丢弃。

SQL>  create table topic
  2   (id number,
  3   first_post_id number,
  4   last_post_id number,
  5   othercontent varchar(10)
  6   );

表已创建。

SQL>  create table post
  2   (id number,
  3   topic_id number,
  4   othercontent varchar(10)
  5   );

表已创建。

SQL> alter table topic add constraint pk_a primary key (id);

表已更改。

SQL> alter table post add constraint pk_b foreign key (topic_id) references topic(id) on delete casc
ade;

表已更改。

SQL> insert into topic values ('1','2','3','haha');

已创建 1 行。

SQL> insert into post values ('4','1','hehe');

已创建 1 行。

SQL> commit;

提交完成。

SQL> select * from topic;

        ID FIRST_POST_ID LAST_POST_ID OTHERCONTE
---------- ------------- ------------ ----------
         1             2            3 haha

SQL> select * from post;

        ID   TOPIC_ID OTHERCONTE
---------- ---------- ----------
         4          1 hehe

SQL> delete from topic where id='1';

已删除 1 行。

SQL> select * from topic;

未选定行

SQL> select * from post;

未选定行

SQL>

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10742223/viewspace-237971/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/10742223/viewspace-237971/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值