/ / MySQL Transofrming table do macierzy bez wartości null - mysql, sql, matrix, pivot-table

MySQL Transofrming table do macierzy bez wartości null - mysql, sql, matrix, pivot-table

Mam tabelę z krajami i tłumaczeniami w różnych językach, coś podobnego (może niektóre dane mogą być błędne, ale są tylko przykładowe wartości):

lanId, countryId, name, translation
1,        1,      Spain,  Spain
1,        2,      France, France
1,        3,      Italy,  Italy
2,        1,      Spain,  España
2,        2,      France, Francia
2,        3,      Italy,  Italia
3,        1,      Spain,  Espagne
3,        2,      France, France
3,        3,      Italy,  Italie

To, czego potrzebuję, to macierz przedstawiająca jedną kolumnę dla języka, podobną do tej:

countryId, countryName, es,     fr,
1,           spain,    españa,  espagne
2,           france,   francia, france
3,           italy,    italia,  italie

Próbowałem użyć zdania CASE:

SELECT countryId,
case WHEN idLan =1 THEN translation  end as en,
case WHEN idLan =2 THEN translation END as es,
case WHEN idLan =3 THEN translation END as fr,
FROM translations

Ale otrzymuję wiele wartości NULL w każdej kolumnie, tak jak poniżej:

countryId, en,    es,     fr
1,       spain,  NULL,    NULL
2,       france, NULL,    NULL
3,       Italy,  NULL,    NULL
1,       NULL,   españa,  NULL
2,       NULL,   francia, NULL
3,       NULL,   italia,  NULL...

Jak mogę uzyskać taką macierz, ale unikając wartości pustych?

countryId, en,    es,       fr
1,       spain,  españa,   espagne
2,       france, francia,  france
3,       Italy,  italia,   italie

Czołgi.

Odpowiedzi:

1 dla odpowiedzi № 1

Wypróbuj następujące zapytanie pivot:

SELECT
countryId,
name,
MAX(CASE WHEN lanId = 1 THEN translation END) AS en,
MAX(CASE WHEN lanId = 2 THEN translation END) AS es,
MAX(CASE WHEN lanId = 3 THEN translation END) AS fr
FROM translations
GROUP BY
countryId,
name

Wydajność:

wprowadź opis obrazu tutaj

Demo tutaj:


1 dla odpowiedzi nr 2

Musisz pogrupować według identyfikatora kraju:

SELECT countryId,
case WHEN lanId = 1 THEN translation END as en,
case WHEN lanId = 2 THEN translation END as es,
case WHEN lanId = 3 THEN translation END as fr
FROM translations
GROUP BY countryId