选择除其子类别之外的所有类别

时间:2011-08-04 11:04:53

标签: sql sql-server-2005

我有一个表格类别,父母和子女关系我的表架构如下:

CategoryID       ParentID        CategoryName
1                  0                A
2                  1                B
3                  1                C
4                  2                D
5                  0                E
6                  5                F
7                  5                G
8                  6                I
9                  1                J
10                 0                L

现在当我想选择所有没有ParentId 1且它的Child CategoryID 的类别时,当我传递 CategoryID 1 时,我的输出应该如下所示

CategoryID        ParentID        CategoryName
5                   0                  E
6                   5                  F
7                   5                  G
8                   6                  H
10                  0                  L

我怎么能找到那样的结果。

1 个答案:

答案 0 :(得分:1)

这要点是

  1. 选择从类别1下载的所有记录
  2. 将其排除在最终结果之外
  3. SQL语句

    ;WITH q AS (
        SELECT  CategoryID, ParentID
        FROM    Category
        WHERE   CategoryID =1           
        UNION ALL
        SELECT  c.CategoryID, c.ParentID
        FROM    Category c
                INNER JOIN q ON q.CategoryID = c.ParentID
    )
    SELECT  *
    FROM    Category c
    WHERE   NOT EXISTS (SELECT CategoryID FROM q WHERE q.CategoryID = c.CategoryID)
    

    测试数据

    ;WITH Category (CategoryID, ParentID, CategoryName) AS (
        SELECT  1, 0, 'A'
        UNION ALL SELECT 2, 1, 'B'
        UNION ALL SELECT 3, 1, 'C'
        UNION ALL SELECT 4, 2, 'D'
        UNION ALL SELECT 5, 0, 'E'
        UNION ALL SELECT 6, 5, 'F'
        UNION ALL SELECT 7, 5, 'G'
        UNION ALL SELECT 8, 6, 'I'
        UNION ALL SELECT 9, 1, 'J'
        UNION ALL SELECT 10, 0, 'L'
    )   
    , q AS (
        SELECT  CategoryID, ParentID
        FROM    Category
        WHERE   CategoryID =1           
        UNION ALL
        SELECT  c.CategoryID, c.ParentID
        FROM    Category c
                INNER JOIN q ON q.CategoryID = c.ParentID
    )
    SELECT  *
    FROM    Category c
    WHERE   NOT EXISTS (SELECT CategoryID FROM q WHERE q.CategoryID = c.CategoryID)