使用join,从数据库中找出所有州和州的明智城市

时间:2016-10-06 10:07:58

标签: mysql

使用join

从数据库中找出所有州和州的明智城市

我在数据库中有三个表,即国家,州,城市 我使用主键和外键在它们之间进行映射。 我想要具体的'印度'国家和相关的国家所有州和城市......我该怎么办? 在这里,我正在给我的代码...我创建了......给我任何其他建议

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

3 个答案:

答案 0 :(得分: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 |
+------+-------------+------+---------+-------+

答案 1 :(得分:0)

从sql中找出国家明智的州和州明智城市并不是一个好主意。

你应该使用javascript试试这个just include this file in your required webpage

答案 2 :(得分:0)

请尝试以下操作(很抱歉代码中没有换行符。不知道它是如何工作的。)

syncdb