In my database I have a table called data_countries
with the following structure:
country | population | nearby_country1 | nearby_country2 | nearby_country3
When I run the following query
SELECT DISTINCT data_countries.country, data_countries.population, data_countries.nearby_country1 , data_countries.nearby_country2 , data_countries.nearby_country3
FROM data_countries
WHERE data_countries.country = 'Netherlands'
I get a result that looks something like this
Netherlands | 16570613 | Belgium | Germany | United Kingdom
What I actually want to achieve now is the following. Based on the input 'Netherlands', I also want to return the data in the same stucture for column nearby_country1
nearby_country2
and nearby_country3
.
So concretely, I want to adapt my query to get an output like this:
Netherlands | 16570613 | Belgium | Germany | United Kingdom
Belgium | 10000000 | Netherlands | Other | Other
Germany | 10000000 | Netherlands | Other | Other
United Kingdom | 10000000 | Other | Other | Netherlands
I looked into INNER JOIN
and Subselect
and tried some things but can't seem to get it right. Hopefully someone can put me into the right direction on this one.
Thanks
Yuck. Your data is not normalized so you need to do this with joins. Here is one way if your table is not very big. Note that the country itself is included in the "nearby" countries:
select nearby.*
from data_countries c join
data_countries nearby
on c.country = 'Netherlands' and
nearby.country in (c.country, c.nearby_country1, c.nearby_country2, c.nearby_country3)
order by (nearby.country = 'Netherlands') desc;
If you want to keep the ordering, then change the order by
to:
order by (nearby.country = 'Netherlands') desc,
(nearby.country = c.nearby_country1) desc,
(nearby.country = c.nearby_country2) desc,
(nearby.country = c.nearby_country3) desc
EDIT:
Here is a SQL Fiddle example showing it working (note this uses SQL Server just so I can use the with
syntax).
Normalized means that you have a table called NearbyCountries
, with two data columns. One for the first country and one for the second.