常規樹形表結構
方式一: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<>'韓城市'
結果
刪除節點及包含的所有子節點
轉自:https://www.cnblogs.com/wgx0428/p/13606375.html#3408585068