[英]How to join three tables together in MySQL?
我有一个存储国家,省和城市的表格位置。 我想按城市ID搜索城市; 我也可以看到它的省和国家! 我已经尝试了太多,但是我真的不知道我需要写什么确切的查询。
我的表名是location,这些是我的示例数据字段:
id enName localName type in_location
1 Iran ایران country 0
2 Fars فارس province 1
3 shiraz شیراز city 2
4 marvdasht مرو دشت city 2
我想当我搜索id = 3时得到以下结果:
国家/省/城市
伊朗/法尔斯/设拉子
如何编写此查询? 我知道我必须加入桌子3次,但不知道该怎么做。
我尝试过的代码:
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
陈述应始终放在结尾。 我认为这是您想要的。 不过,您将与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
尽管您尚未指定其他表名称,但是您可以尝试此操作。
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;
该查询可能对您有帮助!
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.