繁体   English   中英

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

[英]find out country wise all states and states wise cities from database using join

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

请使用以下查询
具有以下数据的表-

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

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

您应该使用javascript尝试将其仅包含在所需的网页中

尝试执行以下操作(对不起,代码中没有换行符。不知道其工作原理)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM