select 相同 table 中的链接行

select linked rows in the same table

我正在创建一个分支对话游戏,并使用输出 JSON 和 linklink_path 的对话工具将对话连接在一起。我已经在 PostgreSQL 中解析并插入了这个结构。

我想查询行的子集,比方说从第 1 行开始,然后跟随 link_path 直到 link_path 为空。连续的行可能是乱序的。

例如,在下面的table中,

--

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

Demo on DB Fiddle:

link | link_path | info 
:--- | :-------- | :----
a    | b         | asdjh
b    | c         | uiqwd
c    | null      | isado