【问题标题】:sql - syntax of self-joined tablesql - 自联接表的语法
【发布时间】:2017-03-07 19:25:58
【问题描述】:

我有一个类别表,可以分为 2 个级别:父类别和子类别,如果父类别为 0,则其为父猫,否则为子类别。任何有父母的子,但有些父母可能还没有子。

   categoryID   |  categoryName    |   parentID
---------------------------------------------------
       1        |    cat 1         |        0         (parent cat)
       2        |    cat 2         |        1         (sub of #1)

我想要一张表格,上面列出: categoryID, categoryName, ParentCategoryID, parentCategoryName

如果我进行 INNER JOIN,那么我会失去没有潜艇的父猫。 示例:

SELECT 
    Sub.[categoryName] As SubcatName, Sub.categoryID, 
    Parent.[categoryName] As ParentCatName, Sub.[parentID] AS parentID 
FROM 
    [tblCategories] Parent INNER JOIN [tblCategories] Sub 
ON 
     Sub.[parentID] = Parent.[categoryID]

如果我执行 LEFT OUTER JOIN (Parent --> Sub),那么我会得到子类别作为父项。

如果我执行 LEFT OUTER JOIN (parent --> Sub) - 那么我再次只得到那些有父猫的类别。

有人能推荐一个查询语法吗?

【问题讨论】:

    标签: sql-server


    【解决方案1】:

    使用递归 cte:

    ;with cte as (
    -- anchor elements: where parentId = 0
      select 
          categoryId
        , categoryName
        , parentId
        , parentName = convert(varchar(32),null)
      from t
      where parentId = 0
      -- recursion begins here
      union all 
      select 
          c.categoryId 
        , c.categoryName
        , c.parentId
        , parentName = p.categoryName
      from t c
        inner join cte as p on c.parentId= p.categoryId
    )
    -- we select all the results 
    select *
    from cte 
    

    【讨论】:

      【解决方案2】:
       SELECT cat2.[categoryId]
        ,cat2.[categoryName]
        ,cat2.[parentid]
        ,cat1.categoryName
       FROM [category] cat1
       RIGHT JOIN [category] cat2
           on cat2.parentid = cat1.categoryId
      

      original entries

      【讨论】:

        猜你喜欢
        • 2016-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-29
        • 2020-12-01
        • 2019-07-26
        • 1970-01-01
        • 2017-02-24
        相关资源
        最近更新 更多