gpt4 book ai didi

sql - 类别的递归选择

转载 作者:行者123 更新时间:2023-11-29 11:34:37 25 4
gpt4 key购买 nike

在我的数据库中有下表:

Category: {[Name: VarChar, TopCategory: VarChar]}

表格内容如下:

Contents of the Table

现在我需要在递归语句中使用 with-clause 从类别 Computer Science 的所有子类别中获取所有名称。这必须使用 SQL 来完成,不能使用 PHP 或其他编程语言。

所有子类别不仅意味着直接后代,而且在这种情况下还包括 C++Java我该怎么做?

目前我所拥有的:

SELECT name FROM category WHERE (topcategory = 'Computer Science')

最佳答案

开始吧:

WITH RECURSIVE cte_t1 (name, topcategory, Level)
AS
(
SELECT name, topcategory, 0 AS Level
FROM Category
WHERE topcategory = N'ComputerScience'
UNION ALL
SELECT t1.name, t1.topcategory, Level + 1
FROM Category t1, cte_t1 ctet1
WHERE ctet1.name= t1.topcategory
)
SELECT Level, topcategory, name
FROM cte_t1

关于sql - 类别的递归选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12635405/

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