SQL递归查询

发布于 2024-10-12 04:15:21 字数 689 浏览 1 评论 0原文

我有一个表类别,

1) Id
2) 类别名称
3) CategoryMaster

,数据为:

1 电脑 0
2 软件1
3 多媒体1
4 动画3
5 健康 0
6 Healthsub 5

和我创建了递归查询:

 ;WITH CategoryTree AS
 (
  SELECT *, CAST(NULL AS VARCHAR(50)) AS ParentName, 0 AS Generation    
  FROM dbo.Category    
  WHERE CategoryName = 'Computers'

  UNION ALL        

  SELECT Cat.*,CategoryTree.CategoryName AS ParentName, Generation + 1    
  FROM dbo.Category AS Cat  INNER JOIN 
  CategoryTree ON Cat.CategoryMaster = CategoryTree.Id
 )

 SELECT * FROM CategoryTree

我从父类别到底部获得结果,就像我获得计算机的所有子类别一样,

但我想要从下到上的结果,例如从动画到计算机,请一些有人建议我正确的方向。

先感谢您 :)

I have a Table Category,

1) Id
2) CategoryName
3) CategoryMaster

with data as:

1 Computers 0
2 Software 1
3 Multimedia 1
4 Animation 3
5 Health 0
6 Healthsub 5

and i have created recursive query as:

 ;WITH CategoryTree AS
 (
  SELECT *, CAST(NULL AS VARCHAR(50)) AS ParentName, 0 AS Generation    
  FROM dbo.Category    
  WHERE CategoryName = 'Computers'

  UNION ALL        

  SELECT Cat.*,CategoryTree.CategoryName AS ParentName, Generation + 1    
  FROM dbo.Category AS Cat  INNER JOIN 
  CategoryTree ON Cat.CategoryMaster = CategoryTree.Id
 )

 SELECT * FROM CategoryTree

I get the results for parent category to bottom, like i get all sub categories for computer

but i want the results from bottom-up like from Animation to Computers, please can some one suggest me right direction.

Thank you in advance :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

软糯酥胸 2024-10-19 04:15:21

只需交换 join 子句中的字段即可:

WITH CategoryTree AS
        (
        SELECT  *, 0 AS Generation    
        FROM    dbo.Category
        WHERE   CategoryName = 'Animation'
        UNION ALL
        SELECT  Cat.*, Generation + 1    
        FROM    CategoryTree
        JOIN    dbo.Category AS Cat
        ON      Cat.Id = CategoryTree.CategoryMaster
        )
SELECT  *
FROM    CategoryTree

Just swap the fields in the join clause:

WITH CategoryTree AS
        (
        SELECT  *, 0 AS Generation    
        FROM    dbo.Category
        WHERE   CategoryName = 'Animation'
        UNION ALL
        SELECT  Cat.*, Generation + 1    
        FROM    CategoryTree
        JOIN    dbo.Category AS Cat
        ON      Cat.Id = CategoryTree.CategoryMaster
        )
SELECT  *
FROM    CategoryTree
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文