SQL 樹形結構遞迴查詢

2022-01-11 15:48:21 字數 1433 閱讀 3553

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<>'韓城市'

結果

( 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)

遞迴查詢樹形結構的SQL

一.在oracle中可使用start with.connect by子句 start with.connect by子句遞迴查詢一般用於乙個表維護樹形結構的應用。建立示例表 create table tbl test id number,name varchar2 100 byte pid numb...

java 遞迴查詢樹形結構

什麼叫做遞迴呢?程式設計師呼叫自身的程式設計技巧叫做遞迴。例如區域的省市縣聯動,中,通過查詢省的id,查處這個省下邊的所有市以及市下邊的縣等操作,就可以通過遞迴演算法來查詢 我使用的框架是ssm,主要是在service層做判斷 private listgetregionlist string id ...

遞迴查詢與樹形結構

關係數型據庫 如oracle 的資訊通常儲存在乙個或多個表中。為表示現實世界中的有多重級聯關係的概念,通常我們會把這些物件儲存於同一張表,並通過一組字段 field 表達它們之間的隸屬關係。譬如常見的部門資訊 tb dept dept id,dept name,parent id 名稱含義 dept...