开发者

TSQL A problem with categories tree

I have a problem with recursive CTE query

Let's say that I have that category tree (Category table)

TSQL A problem with categories tree

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

TSQL A problem with categories tree

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:

TSQL A problem with categories tree

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜