我目前正在将查询从Oracle导出到PostgreSQL,而我仍然坚持使用这个用于对目录进行排序的查询:
WITH RECURSIVE R AS (
SELECT ARRAY[ID] AS H
,ID
,PARENTID
,NAME
,1 AS level
FROM REPERTORIES
WHERE ID= (SELECT Min(ID) FROM REPERTORIES)
UNION ALL
SELECT R.H || A.ID
,A.ID
,A.PARENTID
,A.NAME
,R.level + 1
FROM REPERTORIES A
JOIN R ON A.PARENTID = R.ID
)
SELECT NAME
,ID
,PARENTID
, level
FROM R
ORDER BY H
它部分工作,每个子目录都放在他的父目录或共享同一个父目录的目录之后(一个目录可以有子目录,也有子目录等等)
但是我还需要通过NAME对同一级别的目录进行排序(当然,它们的子目录仍然在它们旁边)
我怎样才能做到这一点?
提前致谢(如果我的英语很难理解,那就很抱歉)
编辑:这是ORignial Oracle查询:
SELECT NAME, ID, PARENTID, level
FROM REPERTORIES
CONNECT BY PRIOR ID = PARENTID
START WITH ID = (SELECT Min(ID) FROM REPERTORIES)
ORDER SIBLINGS BY NAME
答案 0 :(得分:1)
与构造h
的方式类似,构造一个包含路径名称和顺序的数组。
答案 1 :(得分:-1)
“H by order”让我失去了一个循环,但是...... 通常,您需要在查询的递归部分进行排序,以使它们“正确”分组。
WITH RECURSIVE R AS (
SELECT ARRAY[ID] AS H
,ID
,PARENTID
,NAME
,1 AS level
FROM REPERTORIES
WHERE ID= (SELECT Min(ID) FROM REPERTORIES)
UNION ALL
SELECT R.H || A.ID
,A.ID
,A.PARENTID
,A.NAME
,R.level + 1
FROM REPERTORIES A
JOIN R ON A.PARENTID = R.ID
order by name
)
SELECT NAME
,ID
,PARENTID
, level
FROM R