I have the following mysql table with sample data as follows:
id location parentid
1 UK 0
2 East Anglia 1
3 Cambridgeshire 2
4 Norfolk 2
5 Suffolk 2
6 East Midlands 1
7 Derbyshire 6
8 Leicestershire 6
9 EU Countries 0
10 Austria 9
11 Belgium 9
I want to generate a query whereby I can get a list of locations by location name but the location should include any parent location. e.g.
A search for folk
should return:
id location
4 Norfolk, East Anglia, UK
5 Suffolk, East Anglia, UK
A search for East
should return:
id location
2 East Anglia, UK
6 East Midlands, UK
A search for Bel
should return:
id location
11 Belgium
In the above we are excluding concatanting EU countries
Obviously the following doesnt work:
select c.id, CONCAT_WS(', ', c.location, p.location, pp.location) as location
from tbl_locations c
outer left join tbl_locations p on p.id = c.parentid
outer left join tbl_locations pp on pp.id = p.parentid
where c.location like '%whatever%'