首页 > 解决方案 > SQL 选择单行“历史”中的所有行

问题描述

我有一个看起来像这样的表:

ID | PARENT_ID
--------------
0  | NULL
1  | 0
2  | NULL
3  | 1
4  | 2
5  | 4
6  | 3

作为一个 SQL 菜鸟,我不确定我是否可以在一个命令中完成我想要的。

我想要的是从第 6 行开始,递归地遵循“历史”,使用 PARENT_ID 列来引用 ID 列。

结果(在我看来)应该类似于:

6|3
3|1
1|0
0|NULL

我已经尝试过这样的事情:

SELECT T1.ID 
FROM Table T1, Table T2 
WHERE T1.ID = 6 
   OR T1.PARENT_ID = T2.PARENT_ID;

但这只是给了我一个奇怪的结果。

标签: sqlsqlite

解决方案


带一个recursive cte.
如果你想从最大值开始id

with recursive cte (id, parent_id) as (
  select t.*
  from (
    select *
    from tablename
    order by id desc
    limit 1
  ) t
  union all
  select t.*
  from tablename t inner join cte c
  on t.id = c.parent_id
)  

select * from cte

请参阅演示
如果您想具体从id = 6

with recursive cte (id, parent_id) as (
  select *
  from tablename
  where id = 6
  union all
  select t.*
  from tablename t inner join cte c
  on t.id = c.parent_id
)
select * from cte; 

请参阅演示
结果:

| id  | parent_id |
| --- | --------- |
| 6   | 3         |
| 3   | 1         |
| 1   | 0         |
| 0   |           |

推荐阅读