This will get your data, using your current table structure:
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'
But Really:
You should be normalizing your database into three separate tables:
City
State
County
This will make using your data, and writing queries - muchh simpler and readable.
The tables would look something like this:
State
ID Name
1 California
2 Texas
County
ID Name
1 Los Angeles
2 San Diego
3 Harris
City
ID StateID CountyID Name
1 1 1 Los Angeles
2 1 2 San Diego
3 2 3 Houston
Hopefully you can see how much easier that is to manage things. You can choose to add a StateID
to the County
table to normalize further. But I'll keep my answer short.
Select the same data from these new tables with a similar query:
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