合并同一个表中的2个字段?

时间:2016-01-12 12:58:12

标签: mysql join internationalization union

我正在翻译表格。我想合并翻译,以便我有另一种语言的后备。

tbl `cms`
+----+-------+--------+
| id | other | other1 |
+----+-------+--------+
|  1 | na    | na     |
|  2 | na    | na     |
+----+-------+--------+

tbl `translations`
+--------+--------+-------------+--------+
| cms_id | locale |     key     | value  |
+--------+--------+-------------+--------+
|      1 | en     | title       | Coffee |
|      1 | pl     | title       | Kawa   |
|      2 | en     | description | Black  |
|      2 | pl     | description |        |
+--------+--------+-------------+--------+

在此示例中,如果用户使用波兰语,因为当前没有description字段的条目,我想输出英文“Black”。

SELECT * 
FROM cms
LEFT JOIN translations t_en ON cms.id = t_en.cms_id AND locale = 'en'
LEFT JOIN translations t_pl ON cms.id = t_pl.cms_id AND locale = 'pl'
FROM translations

现在我想合并联接中的translations.value字段,我可以通过union来完成吗?或者我可以使用JOIN方法吗?

SELECT 
t_en.value
UNION
t_pl.value
FROM cms
LEFT JOIN translations t_en ON cms.id = t_en.cms_id AND locale = 'en'
LEFT JOIN translations t_pl ON cms.id = t_pl.cms_id AND locale = 'pl'
FROM translations

2 个答案:

答案 0 :(得分:2)

您可以使用加入方法。您可以在COALESCE()中使用SELECT。如果您想要优先考虑Polist值,请将其放在COALESCE()

SELECT cms.id, COALESCE(t_pl.value, t_en.value)
FROM cms LEFT JOIN
     translations t_en
     ON cms.id = t_en.cms_id AND t_en.locale = 'en' LEFT JOIN
     translations t_pl
     ON cms.id = t_pl.cms_id AND t_pl.locale = 'pl';

我应该注意COALESCE()从参数列表中返回第一个非NULL值,因此如果您愿意,可以添加其他语言。

答案 1 :(得分:0)

在您的示例中,您应该使用CASE声明

SELECT 
    CASE 
        WHEN t_pl.value IS NOT NULL AND t_pl.value != '' THEN t_pl.value 
        ELSE t_en.value
    END AS value

FROM cms
LEFT JOIN translations t_en ON cms.id = t_en.cms_id AND locale = 'en'
LEFT JOIN translations t_pl ON cms.id = t_pl.cms_id AND locale = 'pl'
FROM translations