简体   繁体   English

在层次结构表PostgreSQL上选择查询

[英]Select query on a Hierarchy Table PostgreSQL

I was trying to make a recursive select query in postgreSQL, I tried to read a few articles but I couldn't really get the solution out of them... either it's multi-table hierarchy or on another dialect to which then I can't translate to Postgres. 我试图在postgreSQL中进行递归选择查询,我试图阅读一些文章,但我无法真正从中获得解决方案……它是多表层次结构,还是我可以使用的另一种方言? t转换为Postgres。

This is what I've come up with upon now but it seems to retrieve only one column so something is not quite working 这是我现在想出的,但似乎只检索一列,所以有些事情行不通

WITH RECURSIVE authorities(role_id, role_name, fk_above_role) AS (
SELECT role_id,role_name,fk_above_role
FROM roles
WHERE role_id=1
UNION ALL
SELECT h.id_role, h.role_name, h.fk_above_role
FROM roles h
WHERE h.role_id= h.fk_above_role
)
SELECT * FROM authorities LIMIT 2;

I've set the limit to 2 for just to try. 我已将限制设置为2,仅供尝试。 So basically let's say I've got a table made like so 所以基本上可以说我有一个像这样的桌子

role_id   |    role_name    |   fk_above_role
1              HRManager        null
2              Recruiter        1

In this case the recursive query I made, was to retrieve all the HRManager sub roles, how can I do this? 在这种情况下,我进行的递归查询是检索所有HRManager子角色,我该怎么做? I'll need to get eventually also the recruiter sub roles that are considered also HRManager sub_roles. 最终,我还需要获得被视为HRManager sub_roles的招聘者子角色。 What am I doing wrong? 我究竟做错了什么?

You need to join to the recursive CTE in the recursive part of the UNION: 您需要在UNION的递归部分中加入递归CTE:

WITH RECURSIVE authorities(role_id, role_name, fk_above_role) AS (
  SELECT role_id,role_name,fk_above_role
  FROM roles
  WHERE role_id = 1
  UNION ALL
  SELECT child.id_role, child.role_name, child.fk_above_role
  FROM roles child
     JOIN authorities parent on child.fk_above_rold = parent.role_id
)
SELECT * 
FROM authorities LIMIT 2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM