PostgreSQL - 在oracle中使用“start with”和“connect by”迁移查询

时间:2014-06-04 13:35:27

标签: oracle postgresql connect-by

我在oracle中有以下查询。我想将其转换为PostgreSQL表单。有人可以帮我解决这个问题,

SELECT user_id, user_name, reports_to, position 
FROM   pr_operators
START WITH reports_to = 'dpercival'
CONNECT BY PRIOR user_id = reports_to;

1 个答案:

答案 0 :(得分:5)

这样的事情应该适合你(SQL Fiddle):

WITH RECURSIVE q AS (
    SELECT po.user_id,po.user_name,po.reports_to,po.position
      FROM pr_operators po
     WHERE po.reports_to = 'dpercival'
    UNION ALL
    SELECT po.user_id,po.user_name,po.reports_to,po.position
      FROM pr_operators po
      JOIN q ON q.user_id=po.reports_to
)
SELECT * FROM q;

你可以read more on recursive CTE's in the docs

注意:您的设计看起来很奇怪 - reports_to包含字符串文字,但它与user_id一致,典型的类型为integer。< / p>