SQL 樹形結構遞歸查詢


 

常規樹形表結構

方式一:WITH AS

WITH AS短語,也叫做子查詢部分(subquery factoring),定義一個sql 片段,改sql 片段會被整個sql語句用到。其中最實用的功能就是數據的遞歸,遞歸的原理:遞歸包括至少兩個查詢,一個查詢作為遞歸的基點也就是起點,另一個查詢作為遞歸的成員。

查詢某個節點級所屬子節點

 
with temp as
(
	select * from Base_Module where FullName='陝西省'
	union all
	select c.* from Base_Module as c,temp t where c.ParentId=t.Id
)
select * from temp

 

結果

注意點:

語句1隱式的內連接,沒有INNER JOIN,形成的中間表為兩個表的笛卡爾積。

select c.* from Base_Module as c,temp t where c.ParentId=t.Id

 

語句2顯示的內連接,一般稱為內連接,有INNER JOIN,形成的中間表為兩個表經過ON條件過濾后的笛卡爾積。

select b.* from a inner join Base_Module b on a.ParentId=b.Id

 

查詢某個節點的所有上層機構

 
with a as
(
	select * from Base_Module where FullName='韓城市'
	union all
	select b.* from a, Base_Module b where a.ParentId=b.Id
)
select * from a where a.FullName<>'韓城市'

 

結果

刪除節點及包含的所有子節點

with temp as
(
	select Id,ParentId from Base_Module where FullName='陝西省'
	union all
	select a.Id,a.ParentId from Base_Module as a inner join temp b on a.ParentId=b.Id
) delete from Base_Module where Id in (select Id from temp) 

 

轉自:https://www.cnblogs.com/wgx0428/p/13606375.html#3408585068


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM