[英]How can I order hierarchy trees by branch in a select statement returning all hierarchy levels?
This is my current SQL: 这是我目前的SQL:
SELECT filter_id, parent_id, level_id, match
FROM t_filters
ORDER BY level_id;
It shows the following: 它显示以下内容:
ID PARENT RANK FILTER VALUE
10004 1 HQ
10002 1 Finance
10006 1 IT
10003 10006 2 HQ - Central
10005 10004 2 HQ - Non Core & Legacy
10001 10005 3 Non Core
My first attempt here orders the records by the hierarchy_level_id, which is basically the rank. 我在这里的第一次尝试通过hierarchy_level_id命令记录,这基本上是排名。
Note the parent field is null where the record is at the top of the hierarchy. 请注意,父字段为空,其中记录位于层次结构的顶部。
Also, the branch can have any length from 1 to 8 entries (8 is the current max but could theoretically increase by 1 or 2). 此外,分支可以具有1到8个条目的任何长度(8是当前最大值,但理论上可以增加1或2)。
What I want to show is the following, which should use the parent field to collate the individual branches of the hierarchy together: 我想要展示的是以下内容,它应该使用父字段来整理层次结构的各个分支:
ID PARENT RANK FILTER VALUE
10004 1 HQ
10005 10004 2 HQ - Non Core & Legacy
10001 10005 3 Non Core
10002 1 Finance
10006 1 IT
10003 10006 2 HQ - Central
The following solution orders siblings by id
. 以下解决方案按id
排序兄弟姐妹。 In your comments, you've mentioned wanting to order siblings by (filter) value
. 在你的评论中,你提到想要通过(过滤) value
来订购兄弟姐妹。 Just replace the relevant expression to achieve this. 只需替换相关表达式即可实现此目的。
Use recursive SQL, Oracle syntax: 使用递归SQL,Oracle语法:
SELECT *
FROM t_filters
START WITH parent IS NULL
CONNECT BY parent = PRIOR id
ORDER SIBLINGS BY id
Alternatively, SQL standard syntax (the standard and some databases would require a RECURSIVE
keyword, but Oracle doesn't allow it). 或者,SQL标准语法(标准和一些数据库需要RECURSIVE
关键字,但Oracle不允许)。 A bit more tedious, but more extensible: 更乏味,但更具可扩展性:
WITH /* RECURSIVE */ r (id, parent, rank, value, path) AS (
SELECT id, parent, rank, value, '' || id
FROM t_filters
WHERE parent IS NULL
UNION ALL
SELECT f.id, f.parent, f.rank, f.value, r.path || '/' || f.id
FROM r
JOIN t_filters f ON r.id = f.parent
)
SELECT *
FROM r
ORDER BY path
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.