SQL递归查询实现跟帖盖楼效果


网易新闻的盖楼乐趣多,某一天也想实现诸如网易新闻跟帖盖楼的功能,无奈技术不佳(基础不牢),网上搜索了资料才发现SQL查询方法有一种叫递归查询,整理如下:

一、查询出 id = 1 的所有子结点

with my1 as
(select * from table where id = 1  union all 
select table.* from my1, table 
where my1.id = table.fatherId) 
select * from my1    

结果包含1这条记录,如果不想包含,可以在最后加上:where id <> 1

二、查询出 id = 2 的所有父结点

with my1 as
(select * from table where id = 2  union all select table.* 
from my1, table where my1.fatherId = table.id ) 
select * from my1;  

三、删除 id = 1 的所有子结点(包括id = 1结点)

with my1 as
(select * from table where id = 1  union all select table.* 
from my1, table where my1.id = table.fatherId ) 
delete from table where exists (select id from my1 
where my1.id = table.id) 

SQL递归查询实现跟帖盖楼效果

相关阅读 >>

sql获取第一条记录的方法(sqlserver、oracle、mysql数据库)

oracle 模糊查询及like用法

深入了解sql注入和预防措施

sql修改语句怎么写

对mysql经常使用语句的全面总结(必看篇)

解决plsql developer中数据库插入数据乱码问题(ssm项目开发)

mssql2005 insert,update,delete 之output子句使用实例

sql server 高性能写入的一些经验总结

浅析sql server的嵌套存储过程中使用同名的临时表怪像

mysql多表查询详解下

更多相关阅读请进入《跟帖盖楼》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...