gpt4 book ai didi

SQL递归查询

转载 作者:行者123 更新时间:2023-12-02 16:33:11 25 4
gpt4 key购买 nike

我有一个表格类别,

1) 身份证号
2) 类别名称
3) 类别大师

数据为:

1 电脑 0
2 软件1
3 多媒体1
4 动画3
5 健康 0
6 健康子 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

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

但我想要自下而上的结果,就像从动画到计算机一样,请有人建议我正确的方向。

提前谢谢你:)

最佳答案

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

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

关于SQL递归查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4690324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com