TSQL类别树的问题

时间:2010-12-03 11:39:30

标签: tsql recursion common-table-expression

我有递归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

然后,我想获得该类别ID,wchih没有孩子:类别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 个答案:

答案 0 :(得分: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
)
select child from mq where child not in (select parent from mq)

似乎会提供您想要的输出 - 实际上您对问题的描述几乎采用了这种形式。