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