繁体   English   中英

SQL递归+列连接

[英]SQL recursion + column concatenation

我有一个自引用表(在 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;

是一个 db<>fiddle。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM