sql - 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;
但这只是给了我一个奇怪的结果。
解决方案
带一个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 | |
推荐阅读
- python - cx-Oracle 找不到 Oracle 客户端库
- android - 以横向反应导航打开屏幕
- google-app-engine - 无法为 Java GCP App Engine 项目提供自定义 app.yaml 文件
- visual-studio-code - 单击“解决保存冲突”上的错误按钮后,我可以在 VSCode 上恢复文件的不同版本吗?
- javascript - 使用 StrictTemplate 分配模板引用变量?
- git - 如何管理两个链接的 GitHub 存储库
- database - springboot中如何互换配置数据库
- layer - 删除和编辑 acrobat 图层
- node.js - 如何通过 ARN 获取 AWS 资源的标签?
- runtime-error - 为什么我的简单代码在 spyder 上运行良好,但在 SPOJ 的在线 IDE 上运行良好?