【问题标题】:calculate level of child category in sql query计算sql查询中子类别的级别
【发布时间】:2014-02-12 04:25:33
【问题描述】:

我有一个存储父 ID 和子 ID 的表,一个 ID 可以有多个子类别,子类别可以有更多类别并且可以继续)我有两列“id”和“parentid”来存储该信息。

我需要填充解释类别层次结构级别的第三列“级别”,以便所有没有子级的类别的级别 = 1 ,从父类别继承的子类别的级别 = 2,类似地,从主要父类别进一步继承的子类别继承的所有子类别的级别 = 3 ...这将遵循

如何在此处填充“级别”字段

【问题讨论】:

标签: sql


【解决方案1】:

假设您使用的是 MS SQL SERVER,您可以使用自引用(或递归)CTE

;WITH CTE (id, p_id, level)
AS 
(SELECT s.id, null,1
    FROM table1 s
    where parent_id is null

  UNION ALL

 SELECT s.id,parent_id,m.level + 1
   FROM CTE m
   JOIN table1 s on m.id = s.parent_id
 )
update table1 set level = c.level 
from cte c
where table1.id = c.id;

【讨论】:

    【解决方案2】:

    就像您描述的那样:首先更新所有没有孩子的记录以获得级别 1,然后他们的父母获得级别 2,等等。由于您没有说明 DBMS 也没有说明您要使用的语言,因此以下包含一些伪代码:

    <declare and initialize a variable "@lvl" to 1>
    
    -- SQL:
    update category set level = 1
     where not exists(select 1
                        from category as parent
                       where catergory.parentId = parent.id)
    
    <while the last update updated some rows>
        -- SQL:
        update category set level = @lvl + 1
         where exists(select 1
                        from category as child
                       where child.parentId = category.id
                         and child.level = @lvl)
        <increment lvl by 1>
    <end of while loop>
    

    【讨论】:

      猜你喜欢
      • 2011-12-14
      • 2021-02-19
      • 1970-01-01
      • 2019-02-26
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2021-05-07
      相关资源
      最近更新 更多