TSQL Проблема с деревом категорий - PullRequest
0 голосов
/ 03 декабря 2010

У меня проблема с рекурсивным запросом CTE

Допустим, у меня есть это дерево категорий (Таблица категорий)

alt text

В моем запросе 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

Затем я хочу получить идентификатор категории, у которого нет ребенка: категории 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

почему? Любые идеи будут полезны!

если я отделяю запрос от 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)
    )

1 Ответ

1 голос
/ 03 декабря 2010
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)

Может показаться, что вы хотите - на самом деле ваше описание проблемы почти приняло эту форму.

...