DECLARE @Table TABLE(
URL VARCHAR(200),
URLREDIRECT VARCHAR(200),
)
INSERT INTO @Table SELECT 'URL1','URL2'
INSERT INTO @Table SELECT 'URL2','URL3'
INSERT INTO @Table SELECT 'URL3','URL4'
INSERT INTO @Table SELECT 'URL5','URL6'
INSERT INTO @Table SELECT 'URL6','URL7'
INSERT INTO @Table SELECT 'URL7','URL8'上面的数据定义了一个URL是否被重定向,我想知道一个URL被重定向了多少次,所以URL 1将被重定向3次,因为URL1首先被重定向到URL2,然后再重定向到URL3,然后再重定向到URL4。
发布于 2015-05-26 20:40:20
这可能比您所期望的要多,但是这里有一个递归的CTE实现,它包括一个检查,看看URL是否正在循环,如果被困在循环中,则退出.
create table urls (
url VARCHAR(200),
urlRedirect VARCHAR(200)
)
insert into urls select 'URL1','URL2'
insert into urls select 'URL2','URL3'
insert into urls select 'URL3','URL4'
insert into urls select 'URL5','URL6'
insert into urls select 'URL5','URL7'
insert into urls select 'URL6','URL8'
insert into urls select 'URL9','URL10'
insert into urls select 'URL10','URL11'
insert into urls select 'URL11','URL12'
insert into urls select 'URL12','URL9'
; with recursiveCTE as (
select
url as topURL,
url,
urlRedirect,
cast(url + '->' + urlRedirect as varchar(max)) as tree,
1 as depth,
0 as infiniteLoop
from urls
union all
select
r.topUrl,
t.url,
t.urlRedirect,
cast(r.Tree + '->' + t.urlRedirect as varchar(max)),
r.depth + 1,
case
when r.tree like '%' + t.url + '->' + t.urlRedirect + '%'
then 1
else 0
end as infiniteLoop
from
recursiveCTE r
join urls t
on t.URL = r.urlRedirect
and r.infiniteLoop = 0
),
deepest as (
select
*,
row_number() over (partition by topUrl order by depth desc) as rn
from recursiveCTE
)
select
topURL,
tree,
depth,
infiniteLoop
from deepest
where rn = 1
order by topURLSQL Fiddle在这里
发布于 2015-05-26 20:31:07
SQL小提琴
从这里我想你能得到它。注意:我更改了你的一些数据,因为一些奇怪的东西,比如URL5被指向URL6和7.不确定一个地址如何有两个目的地。
with cte as
(Select url, urlredirect, 1 as lvl
from mtable where url='URL1'
UNION ALL
Select a.url, a.urlredirect, b.lvl+1
from mtable a
inner join cte b on a.url=b.urlredirect
where a.url<>'URL1')
Select * from cte因此,要找到最大重定向,请从lvl获取Select * from cte中的get max
https://stackoverflow.com/questions/30468065
复制相似问题