表 tree
id name pid
1 水果 0
2 苹果 1
3 香蕉 1
4 橘子 1
5 粮食 0
6 大米 5
7 高粱 5
8 玉米 5
9 小米 5
oracle 中的实现方法
Oracle中直接支持,使用语句select * from tablename start with id=1 connect by prior id(子层的列)=pid(属于顶层的列)
语句说明: start with 指定层次开始的条件,即满足这个条件的行即可以作为层次树的最顶层 connect by prior指层之间的关联条件,即什么样的行是上层行的子行(自连接条件)
实例: select * from tree start with id=1 connect by prior id=pid
MSSQL中的实现方法
在MSSQL中需要使用临时表和循环多次查询的方式实现.
创建函数:
create function GetTree(@id int)
returns @t table(
id int,
name varchar(50),
pid int
)
as begin
insert @t select * from recursion where id=@id
while @@rowcount>0
insert @t select a.* from tree as a inner join @t as b
on a.pid=b.id and a.id not in(select id from @t)
return end
使用方法: select * from GetTree(4)
mysql中的实现方法
查询语句:
select b.id,b.name,b.pid from recursion as a, recursion as b where a.id=b.pid and (a.id=1 or b. pid =1)
(查询pid为某个值的所有子节点)
转载请注明:指尖博客 » ORACLE、MSSQL、MYSQL中树结构表递归查询的实现方法