300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > mysql实现评论盖楼的sql_SQL递归查询实现跟帖盖楼效果

mysql实现评论盖楼的sql_SQL递归查询实现跟帖盖楼效果

时间:2023-05-12 16:16:58

相关推荐

mysql实现评论盖楼的sql_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)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。