Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何基于SQL表中的父id获取层次结构子级?_Sql_Postgresql - Fatal编程技术网

如何基于SQL表中的父id获取层次结构子级?

如何基于SQL表中的父id获取层次结构子级?,sql,postgresql,Sql,Postgresql,我正在使用postgresql for laravel api。我有一个包含如下数据的用户表 id parent_id 2 7 2 3 2 14 3 5 3 6 3 17 3 4 3 我很难查询数据,如果我有参数parent_id=2,那么结果数据应该是这样的 id 7 3 14 5 6 17 4 我曾经尝试过这个SQL代码 WITH q AS ( SELECT *

我正在使用postgresql for laravel api。我有一个包含如下数据的用户表

id    parent_id
2       
7     2 
3     2
14    3
5     3
6     3
17    3
4     3
我很难查询数据,如果我有参数parent_id=2,那么结果数据应该是这样的

id

7
3
14
5
6
17
4
我曾经尝试过这个SQL代码

WITH    q AS 
        (
        SELECT  *
        FROM    users
        WHERE   parent_id = 2
        UNION ALL
        SELECT  m.*
        FROM    users as m
        JOIN    q
        ON      m.parent_id = q.id
        )
SELECT  *
FROM    q
但它显示出错误

SQL Error [42P01]: ERROR: relation "q" does not exist¶  Detail: There is a WITH item named "q", but it cannot be referenced from this part of the query.¶  Hint: Use WITH RECURSIVE, or re-order the WITH items to remove forward references.¶  Position: 269
我不知道问题是什么, 有人能帮我解决这个问题吗? 任何帮助都将不胜感激!谢谢

试试下面的方法

select id from users where parent_id=2
union 
select id from users
where parent_id in ( select id from table where parentid=2)