Vague title, sorry.
- Minimal Fiddle: https://www.db-fiddle.com/f/ch7zqbz7vCgkYzYyoDdUjo/1
I am trying to convert client code to "pure" sql in Mysql 5.7 (If it makes any difference - a solution can also apply only to MariaDB 10.1, too).
I have a "codes" table and "code_translations" table. I am now trying to output the "best available translations" for each code in the code table.
If there is request for give me the translations for Code "A" and translations language "de" - try to find a translation with "de" first. If not found - use an available translation for "en" (default fallback). If there is not "en" - take the first translation available determined by the current ordering.
From the fiddle:
CREATE TABLE codes (id SERIAL, code TEXT, country TEXT);
CREATE TABLE code_translations (id SERIAL, code_id INT, language TEXT, label TEXT);
INSERT INTO codes (id, code, country)
VALUES
(1, 'A', 'DE'),
(2, 'B', 'DE'),
(3, 'C', 'DE');
INSERT INTO code_translations (code_id, language, label)
VALUES
(1, 'de', 'A-de'),
(1, 'en', 'A-en'),
(1, 'fr', 'A-fr'),
(2, 'de', 'B-de'),
(2, 'en', 'B-en'),
(3, 'nl', 'C-nl'),
(3, 'ru', 'C-ru');
Basic Select - Yields just all rows:
SELECT c.code,ct.label
FROM codes c
JOIN code_translations ct ON c.id=ct.code_id
-- WHERE ct.language=de
-- WHERE ct.language=fr
-- WHERE ct.language=ru
Desired output:
-- WHERE language = de
-- output should be
-- |A|A-de| -- de is the direct match
-- |B|B-de| -- de is the direct match
-- |C|C-nl| -- first match determined by ordering
-- WHERE language = fr
-- output should be
-- |A|A-fr| -- fr is the direct match
-- |B|B-en| -- no "fr" - take "en"
-- |C|C-nl| -- first match determined by ordering
-- WHERE language = ru
-- output should be
-- |A|A-en| -- no "ru" - take "en"
-- |B|B-en| -- no "ru" - take "en"
-- |C|C-ru| -- ru is the direct match