在甲骨文中:
SELECT LEVEL, Id, Name, LPAD(' ', LEVEL) || Name AS IndentedName
FROM Categories
START WITH
ParentID IS NULL
CONNECT BY
ParentID = PRIOR Id
ORDER SIBLINGS BY
Name
您可以使用IndentedName
或根据LEVEL
伪列自定义格式(它显示每个类别的深度)
PS 最好bad
用作NULL
顶级父 ID,因为您不能使用索引来访问它。改用 a 0
。
更新:
在SQL Server
:
WITH q (id, parentid, name, level, bc) AS
(
SELECT id, parentid, name, 1, CAST(ROW_NUMBER() OVER (ORDER BY name) AS VARCHAR(MAX))
FROM Categories
WHERE ParentID IS NULL
UNION ALL
SELECT c.id, c.parentid, c.name, q.level + 1, q.bc + '.' + CAST(ROW_NUMBER() OVER (ORDER BY c.name) AS VARCHAR(MAX))
FROM q
JOIN Categories c
ON c.parentId = q.id
)
SELECT *
FROM q
ORDER BY
bc
与Oracle
,SQL Server
索引NULL
值不同,因此可以使用 aNULL
来标记最终祖先。