[英]Query all connected ancestors and descendants in a self referencing table
假設我有一個表 'prlines' 與相鄰記錄的自關系:
id | prev_id
------------
1 | NULL
2 | NULL
3 | 1
4 | 2
5 | 3
6 | 5
我想獲取某個記錄的所有連接 ID(上一個/下一個)。 例如:
SELECT `prev_id` FROM `prlines` ... WHERE id = 5;
應該產生這個output:
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;
Output:
prev_id |
---|
3 |
1 |
6 |
7 |
見演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.