Sql递归查询,Sqlserver、Oracle、PG、Mysql

递归分两种:一种由父项向下级递归,另一种是由子项向上级递归。下面就这两种情况做个简单的处理。

假设有一个表treeview,包含字段 id,parentid,text 分别代表id,上级id,描述字段(这里就不把建表sql写出来了)。

一、Sqlserver中的写法

1、由父项递归下级

with cte(id,parentid,text) 
as 
(--父项 
select id,parentid,text from treeview where parentid = 450 --需替换成自己希望查询的id
union all 
--递归结果集中的下级 
select t.id,t.parentid,t.text from treeview as t 
inner join cte as c on t.parentid = c.id 
) 
select id,parentid,text from cte

2、由子级递归父项 

with cte(id,parentid,text) 
as 
(--下级父项 
select id,parentid,text from treeview where id = 450 --需替换成自己希望查询的id
union all 
--递归结果集中的父项 
select t.id,t.parentid,t.text from treeview as t 
inner join cte as c on t.id = c.parentid 
) 
select id,parentid,text from cte

二、Oracle中的写法

 1、由父项递归下级

select a.id,a.parentid,a.text
from treeview a
start with a.id=450 --需替换成自己希望查询的id
connect by prior a.id = a.parentid

 2、由子级递归父项 

select a.id,a.parentid,a.text
from treeview a
start with a.id=450  --需替换成自己希望查询的id
connect by prior a.parentid = a.id

 

三、PostgreSQL中的写法

1、由父项递归下级

with RECURSIVE cte (id,parentid,text)
as
(
select id,parentid,text from treeview where id = 10 --需替换成自己希望查询的id
union all
select t.id,t.parentid,t.text from treeview t,cte t1 where t1.id=t.parentid
)
select * from cte order by rpad(id::varchar,5,'0') asc;

 2、由子级递归父项 

with RECURSIVE cte (id,parentid,text)
as
(
select id,parentid,text from treeview where id = 111 --需替换成自己希望查询的id
union all
select t.id,t.parentid,t.text from treeview t,cte t1 where t1.parentid=t.id
)
select * from cte order by rpad(id::varchar,5,'0') asc;

四、Mysql中的写法

  Mysql的写法很多,网上许多使用自建函数的,这里介绍一种更为通用的方法。

 1、由父项递归下级

SELECT t3.*
FROM
(
	SELECT  t1.id,t1.parentid,t1.text,
	IF ( find_in_set( t1.parentid, @pids ) > 0, @pids := concat( @pids, ',', t1.id ), 0 ) AS ischild
	FROM
	( SELECT id,text,parentid FROM treeview t WHERE 1 = 1 ORDER BY parentid, id ) t1,
	( SELECT @pids := 450 ) t2  --替换成自己想要查询的id
) t3
WHERE t3.ischild != 0

 2、由子级递归父项 

SELECT id,text,parentid,t1.lvl
FROM (
	SELECT
	@r AS _id,
	(SELECT @r := parentid FROM treeview WHERE id = _id) AS parent_id,
	@l := @l + 1 AS lvl
	FROM
	(SELECT @r := 450, @l := 0) vars, --替换成自己想要查询的id
	treeview h
	WHERE @r <> 0
) T1
JOIN treeview T2 ON T1._id = T2.id
ORDER BY id;

  

简单的例子,供大家学习参考。 

 

  

 

posted @ 2018-09-26 08:42  iceriver315  阅读(1140)  评论(0)    收藏  举报