gpt4 book ai didi

SQL 服务器 : get all parent child URL's from a single table

转载 作者:行者123 更新时间:2023-12-01 13:04:50 25 4
gpt4 key购买 nike

我有一个看起来像这样的表:

Slug | Parent | MetaTitle | MetaDescription | MetaKeywords

网站上的 Url 是通过将 slug 附加到父级来构建的,只要父级不为空即可。所以如果我有这样的数据:

Slug            | Parent
-----------------------------------------
Home null
About null
Our-Company About
Our-History Our-Company

我希望能够运行一个可以帮助我的查询

/Home
/About
/About/Our-Company
/About/Our-Company/Our-History

这可能吗?任何帮助都会很棒!!!

最佳答案

可以使用 recursive CTE :

declare @URLTable table (
Slug varchar(50),
Parent varchar(50)
)

insert into @URLTable
(Slug, Parent)
values
('Home', null),
('About', null),
('Our-Company', 'About'),
('Our-History', 'Our-Company')


;with cteURLs as (
select Slug, cast('/' + Slug as varchar(1000)) as URL
from @URLTable
where Parent is null
union all
select u.Slug, cast(c.URL + '/' + u.Slug as varchar(1000)) as URL
from @URLTable u
inner join cteURLs c
on u.Parent = c.Slug
)
select URL from cteURLs

输出是:

URL
-----------------
/Home
/About
/About/Our-Company
/About/Our-Company/Our-History

关于SQL 服务器 : get all parent child URL's from a single table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3814916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com