db2 with語法和遞迴

2021-08-21 22:33:13 字數 2599 閱讀 6452

create

table someplace

( id integer

notnull

primary

key,

parentid int,

name varchar(100)

);insert

into someplace values(001,null,'陝西省');

insert

into someplace values(002,001,'商洛市');

insert

into someplace values(003,001,'西安市');

insert

into someplace values(004,001,'咸陽市');

insert

into someplace values(005,002,'商州區');

insert

into someplace values(006,003,'雁塔區');

insert

into someplace values(007,004,'三原縣');

insert

into someplace values(008,005,'商洛學院');

insert

into someplace values(009,006,'科技二路');

insert

into someplace values(010,005,'蓮湖公園');

insert

into someplace values(011,005,'中心廣場');

insert

into someplace values(012,004,'李靖故居');

insert

into someplace values(013,002,'428');

insert

into someplace values(014,009,'清華軟體園');

with語法可實現簡單的select查詢,有時會遇到對同一資料集多次操作,那麼with語法就相當適合

,例如以下的查詢

with data(id,parentid,name) as

(select id,parentid,name from someplace)

select id,parentid,name from data where id = 5

union

select id,parentid,name from data where id = 6;

檢視結果:

null -- 選擇根節點

union

allselect child.id,child.parentid,child.name from someplace child,data

where child.parentid = data.id-- 遞迴條件

)select id,parentid,name from data ;

檢視結果:

(select id,parentid,name from someplace where id = 5 -- 選擇根節點

union

allselect child.id,child.parentid,child.name from someplace child,data

where child.parentid = data.id-- 遞迴條件

)select id,parentid,name from data ;

檢視結果

這裡可以看到成功獲取到了節點5本身和向下的所有節點

db2 with遞迴語句

with rpl pid,id,name as select root.pid,root.id,root.name from regr root where root.pid 8 union all select child.pid,child.id,child.name from rpl pare...

DB2 With 拆分字串

假設存在表 學生和班級的關係 但是由於表結構的設計的問題,學生的資料的存放是將學生的id用 分隔連線起來存在在資料庫中的,如下圖 班級c1中存在著10個學生,studentdids 列中存的是這10個學生的id,並以逗號分隔。但是由於效率問題,要更改該錶,將每個學生的所在班級的資訊分開存放,clas...

DB2遞迴查詢

遞迴 sql 在 db2 中通過公共表表示式 cte,common table expression 來實現。遞迴 sql 由遞迴 cte 以及對遞迴 cte 結果的查詢組成。那什麼是遞迴 cte 呢?簡言之,如果 cte 中的 fullselect 在 from 子句中引用到 cte 本身,就是遞...