我有自己加入表。该表用于加入最多4级,即。
Region -> Country -> County -> Town
如何获得Town家长的父母。要执行此操作最多两级,这是查询
SELECT t.ShortName AS Town,
(SELECT c.ShortName FROM Locations c
WHERE c.LocationId = t.ParentId) AS County
FROM Locations t
WHERE t.LocationId = 100
现在想要获得郡的父母国家。
答案 0 :(得分:2)
硬编码另一个连接或使用递归CTE。
;with locs as
(
select 1 as level, ShortName, ParentId
from Locations
WHERE LocationId = 100
UNION ALL
SELECT level + 1, l.ShortName, l.ParentId
FROM Locations l
JOIN locs ON locs.ParentId = l.LocationId
)
SELECT * FROM locs;
答案 1 :(得分:2)
使用名称很好的别名假装它的4个独立的表:
SELECT town.ShortName as TownName,
county.ShortName as CountyName,
country.ShortName as CountryName,
region.ShortName as RegionName
FROM Locations town
INNER JOIN Locations county ON town.ParentID = county.LocationID
INNER JOIN Locations country ON county.ParentID = country.LocationID
INNER JOIN Locations region ON country.ParentID = region.LocationID
WHERE town.LocationID = 100
如果不是每个城镇都有县,国家和地区,那么其中一些可能需要LEFT OUTER加入。