SQL递归查询
我有一个表类别,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需交换 join 子句中的字段即可:
Just swap the fields in the join clause: