将递归mysql查询转换为postgresql

col17t5w  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(329)

我想把一个正在工作的mysql查询转换成postgresql。我是postgresql的新手
工作mysql查询:

select  id,
        user_name,
        reported_to 
from    (select * from user_master
         order by reported_to) orrdered,
        (select @pv := 'prathap Achuthan') initialisation
where   find_in_set(reported_to, @pv)
and     length(@pv := concat(@pv, ',', user_name))

http://sqlfiddle.com/#!9/bb94707/2号

wpcxdonn

wpcxdonn1#

在postgresql中,可以使用递归cte实现此查询:

WITH RECURSIVE CTE AS (
  SELECT id, user_name, reported_to
  FROM user_master
  WHERE reported_to = 'prathap Achuthan'
  UNION ALL
  SELECT um.*
  FROM user_master um
  JOIN CTE c ON c.user_name = um.reported_to
)
SELECT *
FROM CTE

输出:

id  user_name               reported_to
7   Sriram Gopalakrishnan   prathap Achuthan
15  Shalini Jagdish         Sriram Gopalakrishnan

sqlfiddle演示

相关问题