SQL多级树形查询(CTE)
表 POI 有 字段 Title CityID
表City 有字段 ID Title ParentCityID(归属City)
求当 烟台下的所有PoiTitle (包含烟台下的子城市中的PoiTitle)
第一步先查询 烟台下所有城市(PCityId指向烟台) CTE
with cte_child(id,title,ParentCityId) as (select id,title,ParentCityId from CMSCity where Title=‘烟台’ union all select a.id,a.title,a.ParentCityId from CMSCity a
inner join cte_child b on ( a.ParentCityId=b.id)) select * from cte_child
第二步操作 poi
修改后sql为:
with cte_child(id,title,ParentCityId) as (select id,title,ParentCityId from CMSCity where Title=‘烟台’ union all select a.id,a.title,a.ParentCityId from CMSCity a
inner join cte_child b on ( a.ParentCityId=b.id)) select CMSPois.CityId,CMSPois.Title from CMSPois inner join cte_child on CMSPois.CityId =cte_child.id