2016-10-06 60 views
0

從數據庫狀態明智的城市找出全國明智所有國家和使用連接找出全國明智所有國家和使用連接

我在數據庫,即國家的三個表從數據庫狀態智慧城市,州,市 我使用主鍵和外鍵給它們之間的映射。 我想要特定的「印度」國家和相關國家的所有州和城市......我該怎麼辦? 在這裏,我給我的代碼...這我created..Give我任何其他建議

select countries.name as country, 
states.name as state, 
cities.name as city 
from states inner join cities 
on states.id = cities.state_id 
inner join countries 
WHERE countries.name='India'; 
+0

看起來你錯過了國家和州之間的連接條件。熟悉你對州和城市的看法。 – mikeyq6

回答

1

請使用以下查詢
表具有低於數據 -

+------+-------+ 
| id | name | 
+------+-------+ 
| 1 | india | 
| 2 | pak | 
| 3 | afgan | 
+------+-------+ 

狀態表

+------+---------+------------+ 
| id | name | country_id | 
+------+---------+------------+ 
| 1 | haryana |   1 | 
| 2 | gujrat |   1 | 
| 3 | himchal |   2 | 
+------+---------+------------+ 

城市表

+------+-------------+----------+ 
| id | name  | state_id | 
+------+-------------+----------+ 
| 1 | bahadurgarh |  1 | 
| 2 | hisar  |  1 | 
| 3 | surat  |  2 | 
| 4 | shimla  |  3 | 
+------+-------------+----------+ 




select cities.id , cities.name ,states.id , states.name ,countries.name from cities left join states on cities.state_id = states.id left join countries on states.country_id = countries.id where countries.name='india' ; 

+------+-------------+------+---------+-------+ 
| id | name  | id | name | name | 
+------+-------------+------+---------+-------+ 
| 1 | bahadurgarh | 1 | haryana | india | 
| 2 | hisar  | 1 | haryana | india | 
| 3 | surat  | 2 | gujrat | india | 
+------+-------------+------+---------+-------+ 
0

嘗試以下(對不起,在代碼中沒有換行。不知道它是如何工作)。

Select countries.name as country, states.name as sta from countries left join cities on states.id= cities.state_id where states.country_id in (SELECT countries.id FROM countries where countries.name='India') 
相關問題