假设 T-SQL 和 MSSQLServer(你没有指定),并且你的Group
表应该看起来像这样:
Id | Name | ParentId
---+------+---------
1 | A | NULL
2 | B | NULL
3 | C | NULL
4 | A1 | 1
5 | A2 | 1
6 | A3 | 1
7 | A11 | 4
8 | A12 | 4
9 | A13 | 4
您可以使用以下递归 CTE 来查找给定组的顶层,例如“A12”:
WITH [Group](Id, Name, ParentId) AS
(
SELECT 1, 'A' , NULL UNION
SELECT 2, 'B' , NULL UNION
SELECT 3, 'C' , NULL UNION
SELECT 4, 'A1' , 1 UNION
SELECT 5, 'A2' , 1 UNION
SELECT 6, 'A3' , 1 UNION
SELECT 7, 'A11', 4 UNION
SELECT 8, 'A12', 4 UNION
SELECT 9, 'A13', 4
), q AS
(
SELECT
*
FROM
[Group]
WHERE
[Name] = 'A12' -- Given 'A12' as the child
UNION ALL
SELECT
g.*
FROM
[Group] g
JOIN
q
ON
q.ParentId = g.Id
)
SELECT
*
FROM
q
WHERE
ParentId IS NULL
此查询返回:
Id | Name | ParentId
---+------+---------
1 | A | NULL