
在oracle中有一种查询叫层次化查询可以实现你所说的功能
select from from table start with id=起始节点 connectionby prior id=parentid;
你可以试试,具体语法可以上网学习一下
有如下数据表
create table tb(id varchar(3) , pid varchar(3) , name varchar(10));
insert into tb values('001' , null , '广东省');
insert into tb values('002' , '001' , '广州市');
insert into tb values('003' , '001' , '深圳市') ;
insert into tb values('004' , '002' , '天河区') ;
insert into tb values('005' , '003' , '罗湖区');
insert into tb values('006' , '003' , '福田区') ;
insert into tb values('007' , '003' , '宝安区') ;
insert into tb values('008' , '007' , '西乡镇') ;
insert into tb values('009' , '007' , '龙华镇');
insert into tb values('010' , '007' , '松岗镇');
假如我们要查询ID为003的数据的所有子节点我们可以使用CTE 递归查询完成
with cte as
(
select aid,aname,apid from tb a where id='003'
union all
select kid,kname,kpid from tb k inner join cte c on cid = kpid
)select from cte
查询结果如下:
003 深圳市 001
005 罗湖区 003
006 福田区 003
007 宝安区 003
008 西乡镇 007
009 龙华镇 007
010 松岗镇 007
用标准sql的with实现递归查询(sql2005以上肯定支持,sql2000不清楚是否支持):
with subqry(id,name,pid) as (
select id,name,pid from test1 where id = 5
union all
select test1id,test1name,test1pid from test1,subqry
where test1pid = subqryid
)
select from subqry;
必须设置 好表的 parentID,ID 第一级设置为 0
with t1 as (
select treelevel = 1, parentID, ID,cast(1 as varchar(20)) ROWNUM from 表 where ID=0
union all
select treelevel = treelevel + 1, t2parentID,t2ID,cast(t1ROWNUM+''+cast(row_number() over (order by t2itemid) as varchar(10)) as varchar(20)) ROWNUM from 表 t2 join t1 on t2parentID=t1id
)
select from t1 order by ROWNUM
以上就是关于有关树状表结构的sql查询问题全部的内容,包括:有关树状表结构的sql查询问题、sql server树形结构表统计每一级树形下的所有子集数,、sqlserver查询树形结构的所有子节点等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)