日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Sql语句之递归查询

發(fā)布時(shí)間:2023/12/10 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Sql语句之递归查询 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

直接進(jìn)入正題

比如一個(gè)表,有id和pId字段,id是主鍵,pid表示它的上級(jí)節(jié)點(diǎn),表結(jié)構(gòu)和數(shù)據(jù):

?

CREATE TABLE [aaa](
?[id] [int] NULL,
?[pid] [int] NULL,
?[name] [nchar](10)
)
GO
INSERT INTO aaa VALUES(1,0,'a')
INSERT INTO aaa VALUES(2,0,'b')
INSERT INTO aaa VALUES(3,1,'c')
INSERT INTO aaa VALUES(4,1,'d')
INSERT INTO aaa VALUES(5,2,'e')
INSERT INTO aaa VALUES(6,3,'f')
INSERT INTO aaa VALUES(7,3,'g')
INSERT INTO aaa VALUES(8,4,'h')
GO
--下面的Sql是查詢出1結(jié)點(diǎn)的所有子結(jié)點(diǎn)
with my1 as(select * from aaa where id = 1
?union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
select * from my1 --結(jié)果包含1這條記錄,如果不想包含,可以在最后加上:where id <> 1
--下面的Sql是查詢出8結(jié)點(diǎn)的所有父結(jié)點(diǎn)
with my1 as(select * from aaa where id = 8
?union all select aaa.* from my1, aaa where my1.pid = aaa.id
)
select * from my1;
?--下面是遞歸刪除1結(jié)點(diǎn)和所有子結(jié)點(diǎn)的語句:
with my1 as(select * from aaa where id = 1
?? union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
delete from aaa where exists (select id from my1 where my1.id = aaa.id)

二:

SQLserver2008使用表達(dá)式遞歸查詢

--由父項(xiàng)遞歸下級(jí)
with cte(id,parentid,text)
as
(--父項(xiàng)
select id,parentid,text from treeview where parentid = 450
union all
--遞歸結(jié)果集中的下級(jí)
select t.id,t.parentid,t.text from treeview as t
inner join cte as c on t.parentid = c.id
)
select id,parentid,text from cte
--由子級(jí)遞歸父項(xiàng)
with cte(id,parentid,text)
as
(--下級(jí)父項(xiàng)
select id,parentid,text from treeview where id = 450
union all
--遞歸結(jié)果集中的父項(xiàng)
select t.id,t.parentid,t.text from treeview as t
inner join cte as c on t.id = c.parentid
)
select id,parentid,text from cte

?

?

轉(zhuǎn)載于:https://www.cnblogs.com/ckblogs/p/3679787.html

總結(jié)

以上是生活随笔為你收集整理的Sql语句之递归查询的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。