Reputation: 448
I have a table location that stores countries, provinces and cities. I want when search a city by its 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:
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:
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.
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
Upvotes: 1
Views: 158
Reputation: 228
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";
Upvotes: 0
Reputation:
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;
Upvotes: 1
Reputation: 776
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.
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
Upvotes: 3