Retrieving i18n data with fallback language

空扰寡人 提交于 2019-11-30 12:13:51

问题


I have to grab i18n text from a database. The default language is English, it has text for everything. But the non-English languages doesn't necessarily have all the desired translations. If a non-English translation for a certain entity/key isn't available in the DB, then I'd like to have it to return the English text instead. So, English is the fallback language here.

The i18n text table look like so (PostgreSQL dialect):

CREATE TABLE translation (
    id SERIAL PRIMARY KEY,
    language_code CHAR(2) NOT NULL,
    key VARCHAR(20) NOT NULL,
    value TEXT NOT NULL,
    CONSTRAINT translation_unique UNIQUE (language_code, key)
)

The data look like this:

INSERT INTO translation 
    (language_code, key, value) 
VALUES
    ('en', 'foo', 'foo in English'),
    ('nl', 'foo', 'foo in Nederlands (Dutch)'),
    ('en', 'bar', 'bar in English')

I'd like to basically do the below pseudo SQL query:

SELECT key, value 
FROM translation 
WHERE (language_code = 'nl' OR IF value IS NULL THEN language_code = 'en')

(actually, the 'nl' value is to be parameterized)

So that it returns the following:

+-----+---------------------------+
| key | value                     |
+-----+---------------------------+
| foo | foo in Nederlands (Dutch) |
| bar | bar in English            |
+-----+---------------------------+

How can I achieve this in a single SQL query?

The DB in question is PostgreSQL, but a RDMBS-agnostic way would be nice.


回答1:


try something like this:

SELECT
    e.key,COALESCE(o.value,e.value)
    FROM Translation                e
        LEFT OUTER JOIN Translation o ON e.key=o.key and o.language_code='nl'
    WHERE e.language_code='en'


来源:https://stackoverflow.com/questions/3238651/retrieving-i18n-data-with-fallback-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!