In a typical system development, we often encounter a kind of problem: check out a record and other records associated with this record is. For example, now you need to check out the Lake District and belongs to the city and province of West Lake District, this time you need to use a recursive SQL query. Here I constructed a data table [tb_Test], its data as follows:
Id Name ParentId
1 浙江省 NULL
2 杭州市 1
3 湖州市 1
4 滨江区 2
5 拱墅区 2
6 西湖区 2
7 吴兴区 3
8 南浔区 3
9 长兴县 3
Down recursive
Suppose we now need to check in Hangzhou and its affiliated county, its code is shown below:
with cte as
(
select Id,Name,ParentId from [tb_Test] where Name='杭州市'
union all
select a.Id,a.Name,a.ParentId from [tb_Test] a inner join cte on a.ParentId=cte.Id
) select * from cte
The results are as follows:
Id Name ParentId
2 杭州市 1
4 滨江区 2
5 拱墅区 2
6 西湖区 2
Recursive up
Suppose now need to query the Lake District and the city and province belongs, its code is as follows:
with cte as
(
select Id,Name,ParentId from [tb_Test] where Name='西湖区'
union all
select a.Id,a.Name,a.ParentId from [tb_Test] a inner join cte on a.Id=cte.ParentId
) select * from cte
The results are as follows:
Id Name ParentId
6 西湖区 2
2 杭州市 1
1 浙江省 NULL