【问题标题】:TSQL A problem with categories treeTSQL 类别树的问题
【发布时间】:2010-12-03 11:39:29
【问题描述】:

我遇到了递归 CTE 查询的问题

假设我有那个类别树(类别表)

在我的 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
    )

输出

然后,我想得到那个没有孩子的类别 ID:类别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)
                ) 
    )

但输出错误:

为什么?任何想法都会有所帮助!

如果我将查询与 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)
    )

【问题讨论】:

    标签: tsql recursion common-table-expression


    【解决方案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)
    

    似乎会给出你想要的输出——事实上你对问题的描述几乎就是这种形式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      相关资源
      最近更新 更多