‘壹’ 关于sql server中的树查询
就用with递归,根节点等级为0,递归时每级+1
‘贰’ sql组织机构树查询
组织等级是四层,应该显示四列才完整
createtablestat(codevarchar(10),parentvarchar2(10),slevelvarchar(10));
INSERTINTOSTATVALUES('中国','0','国家');
INSERTINTOSTATVALUES('浙江省','中国','省');
INSERTINTOSTATVALUES('江苏省','中国','省');
INSERTINTOSTATVALUES('杭州市','浙江省','市');
INSERTINTOSTATVALUES('南京市','江苏省','市');
INSERTINTOSTATVALUES('西湖区','杭州市','县/区');
INSERTINTOSTATVALUES('玄武区','南京市','县/区');
SELECTA.PARENT,A.CODE,B.CODE,C.CODE
FROMSTATA,STATB,STATC
WHEREA.CODE=B.PARENT
ANDB.CODE=C.PARENT
ANDA.PARENT='中国';
PARENTCODECODECODE
----------------------------------------
中国浙江省杭州市西湖区
中国江苏省南京市玄武区
‘叁’ SQL 多级查询(级数不定)
select * from item where itemID=3 union all
select * from item where FDetail=0 and parentID <(select parentID from item where itemID=3)
and substring(Number,1,2) =(select substring(Number,1,2) from item where itemID=3)
and substring(Number,4,2) =(select substring(Number,4,2) from item where itemID=3);
说下思路,先把自己本身一条找出来,然后找他的上级,看你的数据知道parentID 一定小于本身的parentID ,并且是目录的话FDetail=0,如果是其上级目录,他们前边的01.01什么的都是一样的,但是现在有个弊端,就是查询前,要确定这个itemID=3的是属于第几级实体,然后才能采用后边用多少个substring,另一个表itemID=3的条件没用,其实就是一个嵌套,你自己写里边吧
‘肆’ SQL树形层级查询
你好的!
oracle 的start with connect by
别的数据库用cte 递归都能达到你要的效果!
望采纳~
‘伍’ SQL2008怎么实现树形数据查询,语句该怎么写
select 部门名称, (select 部门id from table where 上级部门id=1) from table where 部门名称=总经办
‘陆’ 求教oracle怎么用一个SQL查询多层树形结构
select * from 表 m start with m.id=1 connect by m.parent=prior m.id;
‘柒’ 高难!小白求救,sql 每层有一到三个下级如何查询子树
类似这种语法,你可以参考一下:
WITH leaderCTE as(
SELECT id, name,manager
FROM [lulinghao].[dbo].[YGB]
WHERE name = @name
UNION ALL
SELECT ygb.id, ygb.name,ygb.manager
FROM [lulinghao].[dbo].[YGB] as ygb
inner join leaderCTE lce on lce.manager = ygb.id
)
SELECT case when [id]=100 then 1 when [id]=101 OR [id]=102 then 2 else 3 end as leaderlevel,
name as leadername
FROM leaderCTE
‘捌’ 关于SQL查询树结构数据的语句
方法1:
是否可以有代表层次的字段,若有,直接根据层次字段查询;
方法2:
是否存在以下假设:
非父级的dept_uid的 不可能 在 parent_uid 中出现。
如果假设成立,在查出的所有dept_uid中去掉,所有在在 parent_uid 中出现id,
剩下的就是你要的了。
‘玖’ sql 查询树形数据。
如果树的层数固定就可以用语句查询,但效率比较低。例如你说的三层:
select id,v2.name+name from t1 inner join
(select id,v1.name+name as name from t1 inner join
(select id,name from t1 where parentid = 0) v1 on t1.parentid = v1.id) v2 on t1.parentid = v2.id
‘拾’ sql怎么实现树查询
表格式如下:
cid pid cname
1 0 董事长
2 1 CEO
3 2 销售经理
4 2 IT经理
5 2 运营经理
6 3 销售主管
7 4 IT主管
8 5 运营主管
9 6 业务员
10 7 程序员
11 8 运营员
create function get_detail(
@id int
)returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select @id,@l
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.cid,@l
from table_2 a,@re b
where a.pid=b.id and b.level=@l-1
end
return
end
go
--调用(查询所有的子)
select a.*,level=b.level from table_2 a,get_detail(2)b where a.cid=b.id