【问题标题】:Recursive SQL select递归 SQL 选择
【发布时间】:2012-11-01 21:59:43
【问题描述】:

我有带有类别的项目,这些类别也可以有类别我如何找到第一个父级。比如……

CategoriesTbl
CategoryId | CategoryName   | parent
-------------------------------------
1          | Category1      | 0
2          | Category2      | 1
3          | Category3      | 2

ItemsTbl
ItemId     | CategoryId
-------------------------------------
1          | 3

如何对项目进行选择并将其加入到具有父类别 (CategoryId = 1) 的类别表中。父类别可以嵌套无限深。

【问题讨论】:

    标签: mysql sql hierarchical-data


    【解决方案1】:

    MySQL 不支持递归 SQL 查询。但还有其他存储此类父子数据的方法,允许您使用单个 SQL 查询获取整棵树。

    另见:

    【讨论】:

      【解决方案2】:

      您也许可以使用类似的东西作为起点。

      例如,

      表格

      给孩子排序

      7 6

      5 4

      4 3

      3 2

      2 空

      我的输出应该是

      排名Chiid parid

      1 5 4

      2 4 3

      3 3 2

      4 2 空

      代码片段:

      declare @table table(child int, parid int)
      insert into @table
      select 7, 6 union all
      select 5, 4 union all
      select 4, 3 union all
      select 3, 2 union all
      select 2, null
      
      ;with list
      ( tLevel,
        child,
        parId
      ) as
      ( select
        1 as tLevel,
        child,
        parId
        from @table a
        where parId is null
        union all
        select
        tLevel + 1,
        b.child,
        b.parId
        from list a
        join @table b
         on b.parId = a.child
      )
      select
        rank() over(order by tLevel desc)
          as Rank,
        child,
        parId
      from list
      
      
      
      /* -------- Sample Output: --------
      Rank                 child       parId
      -------------------- ----------- -----------
      1                    5           4
      2                    4           3
      3                    3           2
      4                    2           NULL
      */
      

      【讨论】:

      • 问题被标记为MySQL,没有with语法
      • 没有with,没有递归查询,也没有over()
      猜你喜欢
      • 1970-01-01
      • 2014-02-07
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      相关资源
      最近更新 更多