select 相同 table 中的链接行
select linked rows in the same table
我正在创建一个分支对话游戏,并使用输出 JSON 和 link
和 link_path
的对话工具将对话连接在一起。我已经在 PostgreSQL 中解析并插入了这个结构。
我想查询行的子集,比方说从第 1 行开始,然后跟随 link_path
直到 link_path
为空。连续的行可能是乱序的。
例如,在下面的table中,
- 从第 1 行开始,我找到
link_path = b
、 的行
- 这给了我第 3 行,我找到了
link_path = c
、 的行
- 这给了我第 4 行,第 4 行的
link_path
是 null
,所以我们 return 这个集合:[row 1, row 3, row 4]
--
link link_path info
--------------------------
a b asdjh
w y akhaq
b c uiqwd
c isado
y z qwiuu
z nzabo
在 PostgreSQL 中,如何在不创建查询循环的情况下 select 这样的行?我的目标是表现。
您可以使用递归查询:
with recursive cte as (
select t.* from mytable t where link = 'a'
union all
select t.*
from cte c
inner join mytable t on t.link = c.link_path
)
select * from cte
link | link_path | info
:--- | :-------- | :----
a | b | asdjh
b | c | uiqwd
c | null | isado
我正在创建一个分支对话游戏,并使用输出 JSON 和 link
和 link_path
的对话工具将对话连接在一起。我已经在 PostgreSQL 中解析并插入了这个结构。
我想查询行的子集,比方说从第 1 行开始,然后跟随 link_path
直到 link_path
为空。连续的行可能是乱序的。
例如,在下面的table中,
- 从第 1 行开始,我找到
link_path = b
、 的行
- 这给了我第 3 行,我找到了
link_path = c
、 的行
- 这给了我第 4 行,第 4 行的
link_path
是null
,所以我们 return 这个集合:[row 1, row 3, row 4]
--
link link_path info
--------------------------
a b asdjh
w y akhaq
b c uiqwd
c isado
y z qwiuu
z nzabo
在 PostgreSQL 中,如何在不创建查询循环的情况下 select 这样的行?我的目标是表现。
您可以使用递归查询:
with recursive cte as (
select t.* from mytable t where link = 'a'
union all
select t.*
from cte c
inner join mytable t on t.link = c.link_path
)
select * from cte
link | link_path | info :--- | :-------- | :---- a | b | asdjh b | c | uiqwd c | null | isado