У меня проблема с рекурсивным запросом CTE
Допустим, у меня есть это дерево категорий (Таблица категорий)
![alt text](https://i.stack.imgur.com/QtxNM.png)
В моем запросе 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
)
Выход
![alt text](https://i.stack.imgur.com/fFo3B.png)
Затем я хочу получить идентификатор категории, у которого нет ребенка: категории 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)
)
)
но вывод неправильный:
![alt text](https://i.stack.imgur.com/nmB95.png)
почему? Любые идеи будут полезны!
если я отделяю запрос от 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)
)