I have a problem with recursive CTE query
Let's say that I have that category tree (Category table)
In my CTE query, I search for all children of the 1
category:
(that query works fine)
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
)
The output
Then, I want to get that Category ID, wchih doesn't have a child: categories 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)
)
)
but the output is wrong:
why ? Any ideas will be helpful !
if I separate the query from CTE, everything is OK
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 wh开发者_运维技巧ere c2.parent = c1.child)
)
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
)
select child from mq where child not in (select parent from mq)
Would seem to give the output you want - in fact your description of the problem almost took this form.
精彩评论