我有数据表,其中包含:
|Parent Key| Component Key|
我需要获取所选组件键的所有叶子(父键)。
例如:
| 1 | 2 |
| 1 | 3 |
| 2 | 4 |
| 2 | 5 |
| 6 | 4 |
| 7 | 6 |
| 8 | 11 |
| 9 | 4 |
| 10 | 12 |
对于组件键= 4我想接收
| 1 |
| 7 |
| 9 |
如果选定的组件键已经是叶子(没有组件键==所选组件键的行),我想只返回选定的组件键。
可以仅通过选择来完成吗?
如何以最有效的方式做到这一点?
答案 0 :(得分:0)
尝试类似的东西:
DECLARE @selected INT = 4;
WITH cte
AS
(
SELECT ParentKey, ComponentKey
FROM Table1
WHERE ComponentKey = @selected
UNION ALL
SELECT Table1.ParentKey, Table1.ComponentKey
FROM Table1
INNER JOIN cte ON Table1.ComponentKey = cte.ParentKey
)
SELECT ParentKey FROM cte
WHERE
ParentKey NOT IN (SELECT ComponentKey FROM Table1)
UNION
SELECT ParentKey FROM Table1
WHERE
ParentKey = @selected
AND ParentKey NOT IN (SELECT ComponentKey FROM Table1)
将Table1替换为您的表名。