2010-09-29 53 views
0

我有自我加入表。這張桌子被用來加入4層,即:在自我加入表中獲取父母親

Region -> Country -> County -> 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 

現在想獲得國家是縣的父母。

回答

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; 
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 

如果不是每一個城市有一個縣,國家和地區,然後一些那些可能需要左外連接。