如何在 SQL 中生成通向给定节点的层次结构路径?

How can I generate a hierarchy path in SQL that leads to a given node?(如何在 SQL 中生成通向给定节点的层次结构路径?)
本文介绍了如何在 SQL 中生成通向给定节点的层次结构路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 MS SQL 2008 R2 数据库中,我有这张表:

In my MS SQL 2008 R2 database I have this table:

TABLE [Hierarchy]
[ParentCategoryId] [uniqueidentifier] NULL,
[ChildCategoryId] [uniqueidentifier] NOT NULL

我需要编写一个查询来生成通向给定节点的所有路径.

I need to write a query that will generate all paths that lead to a given Node.

假设我有以下树:

A
-B
--C
-D
--C

这将被存储为:

NULL | A
A    | B
A    | D
B    | C
D    | C

当询问 C 的路径时,我想返回两条路径(或多或少这样写):

When asking for the Paths for C, I would like to get back two paths (written more or less like this):

A > B > C,
A > D > C

推荐答案

这是我的解决方案,Sql小提琴

DECLARE @child VARCHAR(10) = 'C'

    ;WITH children AS
    (

       SELECT 
         ParentCategoryId,
        CAST(ISNULL(ParentCategoryId + '->' ,'')  + ChildCategoryId AS VARCHAR(4000)) AS Path
       FROM Hierarchy
       WHERE ChildCategoryId =  @child
     UNION ALL
       SELECT 
         t.ParentCategoryId,
         list= CAST(ISNULL(t.ParentCategoryId  + '->' ,'')  + d.Path AS VARCHAR(4000))
       FROM Hierarchy t
       INNER JOIN children  AS d
            ON t.ChildCategoryId = d.ParentCategoryId
     )

    SELECT Path 
    from children c
    WHERE ParentCategoryId IS NULL

输出:

A->D->C 
A->B->C 

<小时>

更新:

@AlexeiMalashkevich,要获取 id,你可以试试这个

@AlexeiMalashkevich, to just get id, you may try this

SQL 小提琴

DECLARE @child VARCHAR(10) = 'C'

;WITH children AS
(

   SELECT 
     ParentCategoryId,
     ChildCategoryId  AS Path
   FROM Hierarchy
   WHERE ChildCategoryId =  @child
 UNION ALL
   SELECT 
     t.ParentCategoryId,
     d.ParentCategoryId 
   FROM Hierarchy t
   INNER JOIN children  AS d
        ON t.ChildCategoryId = d.ParentCategoryId
 )

SELECT DISTINCT PATH
from children c

这篇关于如何在 SQL 中生成通向给定节点的层次结构路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)