查询自引用中所有连接的祖先和后代 table

Query all connected ancestors and descendants in a self referencing table

假设我有一个 table 'prlines' 在相邻记录上有自我关系:

id | prev_id
------------
1  | NULL
2  | NULL
3  | 1
4  | 2
5  | 3
6  | 5

我想获取某条记录的所有连接 ID (previous/next)。例如:

SELECT `prev_id` FROM `prlines` ... WHERE id = 5;

应该产生这个输出:

prev_id
-------
3
1
6

我目前正在做的是在 python 中创建一个 while 循环,它生成多个查询以跟踪每条记录的关系。在单个 mysql 查询中实现此目的的任何想法?

您可以使用递归 cte:

with recursive cte(p, c, f) as (
   select p.*, p.prev_id = 5 from prlines p where p.id = 5 or p.prev_id = 5
   union all
   select p.*, c.f from cte c join prlines p on case when c.f then p.prev_id = c.p else p.id = c.c end
)
select case when f then p else c end prev_id from cte where c is not null order by f;

输出:

prev_id
3
1
6
7

参见demo