根据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>
			
			
			
                                                            
                    
把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/
                  
                  
                  
                  
本文通过具体实例展示了如何在SQL中实现级联删除操作,即当删除某个主题时,与其相关的所有帖子也会被一同删除。文章首先创建了两个表:topic和post,并设置外键约束以便在删除topic表中的记录时能够自动删除post表中对应的记录。
          
      
          
                
                
                
                
              
                
                
                
                
                
              
                
                
              
            
                  
					1万+
					
被折叠的  条评论
		 为什么被折叠?
		 
		 
		
    
  
    
  
            


            