递归选择类别

时间:2012-09-28 07:20:36

标签: sql postgresql recursion

在我的数据库中,我有下表:

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

该表具有以下内容:

Contents of the Table

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

所有子类别不仅指直接后代,还包括C++Java 我该怎么做?

到目前为止我做了什么:

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

2 个答案:

答案 0 :(得分:4)

我们走了:

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

答案 1 :(得分:0)

如果你的数据库是oracle,你可以试试(sql fiddle):

select * from category 
  start with name = 'Computer Science'
connect by prior name = top_category
相关问题