Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.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
Postgresql 了解这些值​;在postgres表中相互关联的字段的_Postgresql - Fatal编程技术网

Postgresql 了解这些值​;在postgres表中相互关联的字段的

Postgresql 了解这些值​;在postgres表中相互关联的字段的,postgresql,Postgresql,我有一张这样做的postgres表 | id | name | parent|u id| |1 | Giovanni | 1| |2 |乔瓦尼| 2| |3 |米歇尔| 2| |4 |弗朗西斯卡| 3| |5 |安东尼奥| 3| |6 |米歇尔| 3| |7 |安吉拉| 4| |8 |弗朗西斯卡| 4| |9 |安娜| 5| 一旦选择了名字,我就需要它,例如“Giovanni” 它应该找到我所有的“Giovanni”,并根据父id值找到所有链接的名称。在这一点上,通过查找所有其他与优先顺序相关

我有一张这样做的postgres表

| id | name | parent|u id|
|1 | Giovanni | 1|
|2 |乔瓦尼| 2|
|3 |米歇尔| 2|
|4 |弗朗西斯卡| 3|
|5 |安东尼奥| 3|
|6 |米歇尔| 3|
|7 |安吉拉| 4|
|8 |弗朗西斯卡| 4|
|9 |安娜| 5|
一旦选择了名字,我就需要它,例如“Giovanni” 它应该找到我所有的“Giovanni”,并根据父id值找到所有链接的名称。在这一点上,通过查找所有其他与优先顺序相关的名称进行迭代,例如

| 1 |乔瓦尼| 1|
|2 |乔瓦尼| 2|

|3 | Michele | 2 |考虑以下递归查询:

with recursive cte as (
    select id, name, parent_id from mytable where name = 'Giovanni'
    union all
    select t.id, t.name, t.parent_id
    from cte c
    inner join mytable t on t.parent_id = c.id and t.id <> c.id
)
select * from cte

对不起@GMB你完全正确。我尝试了一个值稍有不同的表。 价值观​​你是这样的吗

| id | name | parent|u id|
|1 |罗西| 13|
|2 |保罗| 13|
|3 | Giovanni | 15|
|4 |乔瓦尼| 16|
|5 |罗西| 16|
|6 |马里奥| 17|
结果应该是

| 3 |乔瓦尼| 15|
|4 |乔瓦尼| 16|
|5 |罗西| 16|
|1 |罗西| 13|
|2 |保罗| 13|

非常感谢您的帮助

谢谢您的回答,我尝试了这个问题,但我得到了以下结果:| 1 | Giovanni | 1 | 2 | Giovanni | 2 |@Wemapp:那将令人惊讶。不过,我测试了查询并修复了一些小故障。这里有一把db小提琴供您参考:
with recursive cte as (
    select id, name, parent_id, array[id] path from mytable where name = 'Giovanni'
    union all
    select t.id, t.name, t.parent_id, c.path || t.id
    from cte c
    inner join mytable t on t.parent_id = c.id and t.id <> c.id
)
select * from cte order by path