我有一张类似这样的表:
State_id | County_id| City_id | Name | Additional_Name
-----------------------------------------------------------------
1 | 0 | 0 | California | State
1 | 1 | 0 | Los Angeles | County
1 | 1 | 1 | Los Angeles | City
1 | 2 | 0 | San Diego | County
1 | 2 | 1 | San Diego | City
2 | 0 | 0 | Texas | State
2 | 1 | 0 | Harris | County
2 | 1 | 1 | Houston | City
持续10,000行。我想要完成的是构建一个SELECT语句,该语句将导致:
State | County | City
-------------------------------------------
California | Los Angeles | Los Angeles
California | San Diego | San Diego
Texas | Harris | Houston
如你所见,我想选择每个城市并展示它的州和县。 state_id,county_id,city_id和Additonal_Name列应该是解决此问题的必要条件,但我不知道如何使用它们。
答案 0 :(得分:2)
这将使用您当前的表结构获取您的数据:
SELECT t2.[Name] AS [State]
,t3.[Name] AS County
,t1.[Name] AS City
FROM MyTable t1
JOIN MyTable t2 -- get state
ON t2.State_id = t1.State_id
AND t2.County_id = 0
AND t2.City_id = 0
JOIN MyTable t3 -- get county
ON t3.County_id = t1.County_id
AND t3.State_id = t1.State_id
AND t3.City_id = 0
WHERE t1.City_id > 0 --(or use t1.Additional_Name = 'City'
您应该将数据库规范化为三个单独的表:
City
State
County
这将使您的数据和编写查询变得更简单,更易读。
表格看起来像这样:
<强>国家强>
ID Name
1 California
2 Texas
<强>县强>
ID Name
1 Los Angeles
2 San Diego
3 Harris
<强>城市强>
ID StateID CountyID Name
1 1 1 Los Angeles
2 1 2 San Diego
3 2 3 Houston
希望你能看到管理事物有多容易。您可以选择将StateID
添加到County
表格以进一步规范化。但是我的答案很简短。
使用类似查询从这些新表中选择相同的数据:
SELECT state.[Name] AS [State]
,county.[Name] AS County
,city.[Name] AS City
FROM MyCity city
JOIN MyState state ON state.ID = city.StateID -- get state
JOIN MyCounty county ON county.ID = city.CountyID -- get county