【发布时间】:2010-12-03 11:39:29
【问题描述】:
我遇到了递归 CTE 查询的问题
假设我有那个类别树(类别表)
在我的 CTE 查询中,我搜索 1 类别的所有子项:
(该查询工作正常)
with mq as
(
select c.Id as parent, c.Id as child
from dbo.Category c
where c.Id = 1
union all
select q.child, c.Id
from mq q
inner join dbo.Category c on q.child = c.IdParentCategory
)
输出
然后,我想得到那个没有孩子的类别 ID:类别9,10,12,14,15
with mq as
(
select c.Id as parent, c.Id as child
from dbo.Category c
where c.Id = 1
union all
select q.child, c.Id
from mq q
inner join dbo.Category c on q.child = c.IdParentCategory
where child in
(
select c1.Id
from dbo.Category c1
where not exists(select c2.Id
from dbo.Category c2
where c2.Id = c1.IdParentCategory)
)
)
但输出错误:
为什么?任何想法都会有所帮助!
如果我将查询与 CTE 分开,一切正常
declare @tab table
(parent int, child int);
insert into @tab
select * from mq
delete from @tab
where child in (
select c1.parent
from @tab c1
where not exists(select c2.parent from @tab c2 where c2.parent = c1.child)
)
【问题讨论】:
标签: tsql recursion common-table-expression