sql - 使用递归 SQL 创建自然层次顺序
问题描述
我有一个表格,其中包含具有内部父子关系的类别。
该表如下所示:
ID | ParentID | OrderID
---+----------+---------
1 | Null | 1
2 | Null | 2
3 | 2 | 1
4 | 1 | 1
OrderID
是当前级别内的订单。
我想创建一个递归 SQL 查询来创建表的自然顺序。
这意味着输出将类似于:
ID | Order
-----+-------
1 | 100
4 | 101
2 | 200
3 | 201
感谢任何帮助。
谢谢
解决方案
我不太确定您所说的“自然顺序”是什么意思,但以下查询会为此数据生成您想要的结果:
with t as (
select v.*
from (values (1, NULL, 1), (2, NULL, 2), (3, 2, 1), (4, 1, 1)) v(ID, ParentID, OrderID)
)
select t.*,
(100 * coalesce(tp.orderid, t.orderid) + (case when t.parentid is null then 0 else 1 end)) as natural_order
from t left join
t tp
on t.parentid = tp.id
order by natural_order;
推荐阅读
- angular - 我是否必须为每个本地示例执行“ng new [name]”?
- laravel - 如何正确注册组件而不会出错?Vue Js
- sql - 有条件地设置 SQL 中的 AND/OR 运算符
- c - 在等待时中断 pselect - 多线程
- javascript - Angular中的多维数组手风琴
- java - 我需要将 fldValue 的值分配给 sipNumber。在下面编写的代码中将在哪里完成?
- firebase-realtime-database - Dialogflow 或 Firebase 执行缓慢
- c++ - 自定义迭代器是否有正式的要求列表?
- string - 当它被点击时改变字符串内的单个字符样式
- regex - 在 csv 文件中使用正则表达式去除零