说我有一个像这样的桌子:
id Parentid childid
--------------------------------
1 null 02
2 01 03
3 02 04
4 03 06
5 051 101
6 04 055
比方说,我总是得到一个中间值,因此它既有子节点又有父节点,而此时我不知道它们是什么。例如,给我ID:4.我编写了一个递归查询,它使我同时获得了父母记录和孩子记录,但是我不确定这是否是正确的方法,也是最快的方法。
with x as (
--These are the anchor (the parents)
select *
from table with (nolock)
where id= 4
),
parents as (
SELECT *
FROM x
UNION ALL
SELECT p.*
FROM parents JOIN
table p
ON parents.ID = p.childid
),
children as (
SELECT top 1 *
FROM x
UNION ALL
SELECT p.*
FROM children JOIN
table p
parents.id = p.parentid
)
SELECT distinct *
FROM parents
UNION
SELECT distinct *
FROM children;
这与我希望结果返回的方式一起工作,因此将返回id:1、2、3、4、6,因为它们是ID 4的父级或子级。