SQL递归+列连接

标签 sql sql-server concatenation self-referencing-table

我有一个自引用表(在 SQL Server 中):

Page
==========
Id: int
RelativeUrl: nvarchar(max)
ParentId: int -> FK to pageId

示例数据:

ID | RelativeUrl | ParentId
===============================
1  | /root       | null
2  | /test1      | 1
3  | /test2      | 1
4  | /test3      | 1
5  | /test1-1    | 2
6  | /test1-2    | 2
7  | /test1-1-1  | 5

我想创建一个 SQL 查询来检索具有完整相对 URL 的表的所有页面。 我考虑过使用递归 SQL 查询,但不知道如何连接relativeurl使其成为完整的相对url。

想要的结果:

ID | FullRelativeUrl                | ParentId
===================================================
1  | /root                          | null
2  | /root/test1                    | 1
3  | /root/test2                    | 1
4  | /root/test3                    | 1
5  | /root/test1/test1-1            | 2
6  | /root/test1/test1-2            | 2
7  | /root/test1/test1-1/test1-1-1  | 5

最佳答案

您可以使用递归 CTE:

with cte as (
      select id, convert(varchar(max), relativeurl) as url, 1 as lev
      from page
      where parentid is null
      union all
      select p.id, concat(cte.url, p.relativeurl), lev + 1
      from cte join
           page p
           on p.parentid = cte.id
     )
select cte.*
from cte;

Here是一个数据库<> fiddle 。

关于SQL递归+列连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60655812/

相关文章:

SQL Server T-SQL 使用 FOR XML PATH 将数据导入 XML

sql-server - 当我为列编制索引时,为什么我的 View 变慢了?

c++ - ## 宏参数连接没有像我预期的那样工作

mysql - 如何预定义列值?

mysql - 如何使用固定的值列表进行查询

mysql - 数据库设计和规范化

c# - 插入一张表,获取id并插入另一张表

SQL(简单)逐行连接两个表

Python 3.x - 使用 sum 函数连接列表中的字符串

php - 三个字段的索引/键或 concat() 字段到另一列