I need to join 2 tables.
In the first table (geoname) there is a list of city codes, country codes and area codes. In the second table (alternatename) there is a list of available translations for each city code.
The sqlfiddle example is here: http://sqlfiddle.com/#!9/7df393/1
What I need is: give me an ordered list of cities by name, taking the italian language version if available or the english if it is not available or the NULL language if previous are not available. For each language, take the preferred version if available.
I tried with many queries, but I don't get the expected result. This is the last one:
SELECT g.geonameid, name
FROM geoname g
LEFT JOIN alternatename a ON g.geonameid = a.geonameid AND
(a.lang = 'it' OR a.lang = 'en' OR a.lang = NULL)
WHERE name IS NOT NULL and fcode="PPL"
GROUP BY g.geonameid
ORDER BY isPreferred DESC, name ASC
LIMIT 0,20
The result is
geonameid name
78910 Milan
12345 New York City
34542 Tampere
But I expect
geonameid name
78910 Milano
12345 New York
34542 Tampere
71132 Sanaa
Any help?
Table schema:
CREATE TABLE geoname (
geonameid INT(11) PRIMARY KEY,
country CHAR(2),
fcode VARCHAR(5));
CREATE TABLE alternatename (
id_name INT(11) PRIMARY KEY AUTO_INCREMENT,
geonameid INT(11),
lang CHAR(2),
name VARCHAR(250),
isPreferred TINYINT(1) NULL);
INSERT INTO geoname (geonameid,country,fcode) VALUES
("12345","US","PPL"),
("78910","IT","PPL"),
("34542","FI","PPL"),
("5","IR","PPL"),
("71132","YE","ADM1");
INSERT INTO alternatename (geonameid,lang,name,isPreferred) VALUES
("12345","en","New York City",NULL),
("12345","en","Big Apple",NULL),
("12345","en","New York",1),
("12345","it","La Grande Mela",NULL),
("12345","it","New York",1),
("12345","ru","New York",1),
("78910","en","Milan",1),
("78910","it","Milano",1),
("34542","en","Tampere",NULL),
("5","fa","Yekāhī",NULL),
("71132","ar","صنعاء",NULL),
("71132","fr","Muhafadat Sanaa",NULL),
("71132",NULL,"Sanaa",NULL);
----- EDIT WITH FINAL QUERIES THANKS TO REPLIES ----
SELECT
geonameid
FROM geoname
WHERE fcode='PPL'
LIMIT 0,10
output --> 12345,78910,34542
SELECT
geonameid,
COALESCE(
MAX(CASE WHEN a.lang = 'it' and isPreferred=1 THEN name END),
MAX(CASE WHEN a.lang = 'it' THEN name END),
MAX(CASE WHEN a.lang = 'en' and isPreferred=1 THEN name END),
MAX(CASE WHEN a.lang = 'en' THEN name END),
MAX(name) ) as name
FROM alternatename a
WHERE geonameid IN (12345,78910,34542)
GROUP BY geonameid
ORDER BY name ASC