我必须从数据库中抓取i18n文本.默认语言是英文,它包含所有内容的文字.但非英语语言并不一定具有所需的所有翻译.如果某个实体/键的非英语翻译在数据库中不可用,那么我想让它返回英文文本.所以,英语是这里的后备语言.
i18n文本表格如下(Postgresql方言):@H_403_3@
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) )
数据如下所示:@H_403_3@
INSERT INTO translation (language_code,key,value) VALUES ('en','foo','foo in English'),('nl','foo in Nederlands (Dutch)'),('en','bar','bar in English')
SELECT key,value FROM translation WHERE (language_code = 'nl' OR IF value IS NULL THEN language_code = 'en')
(实际上,’nl’值要被参数化)@H_403_3@
+-----+---------------------------+ | key | value | +-----+---------------------------+ | foo | foo in Nederlands (Dutch) | | bar | bar in English | +-----+---------------------------+
解决方法
尝试这样的东西:
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'