简体   繁体   English

如何在MySQL中将三个表连接在一起?

[英]How to join three tables together in MySQL?

I have a table location that stores countries, provinces and cities. 我有一个存储国家,省和城市的表格位置。 I want when search a city by its id; 我想按城市ID搜索城市; I can see its province and country too! 我也可以看到它的省和国家! I have tried too much but I really don't know what exact query I need to write. 我已经尝试了太多,但是我真的不知道我需要写什么确切的查询。

My table name is location and these are my fields with example data: 我的表名是location,这些是我的示例数据字段:

id             enName         localName   type     in_location
1              Iran              ایران    country          0
2              Fars             فارس      province         1
3              shiraz         شیراز       city             2
4              marvdasht        مرو دشت    city            2

I want when I search id = 3 get this results: 我想当我搜索id = 3时得到以下结果:

country / province / city 国家/省/城市

Iran / Fars / Shiraz 伊朗/法尔斯/设拉子

How I can write this query? 如何编写此查询? I know I must join the table for 3 times but don't know how exactly do that. 我知道我必须加入桌子3次,但不知道该怎么做。

The code I have tried : 我尝试过的代码:

SELECT 
    in_location ,
    enName 
FROM 
    location 
WHERE 
    id = 12321 as a
INNER JOIN
    SELECT 
        * 
    FROM 
        `fzxit_location` as b 
    on a.in_location = b.id

WHERE statment should always come at the end. 陈述应始终放在结尾。 I think this is what your looking for. 我认为这是您想要的。 You'll be fixed for relationships with 3 children or less though. 不过,您将与3个或更少的孩子建立关系。

SELECT a.enName, b.enName, c.enName FROM location as a
LEFT JOIN location as b ON a.in_location = b.id
LEFT JOIN location as c ON b.in_location = c.id
WHERE a.id = 3

Although you have not specified other Tables name, you can try this.. 尽管您尚未指定其他表名称,但是您可以尝试此操作。

select a.countryName, 
       b.proviceName, 
       c.cityName 
from ((country a 
         left join province b on a.countryId = b.countryId) 
         left join city c on a.countryId = c.countryId) 
where id = 3;  

this query may help you! 该查询可能对您有帮助!

select from p.province_name,
            ct.country_name,
            c.city_name 
from city as c 
   INNER JOIN provinces as p ON c.province_id=p.province_id 
   INNER JOIN countries as ct ON c.country_id = ct.country_id 
where c.city_id = "requested value";

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

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