2

我有两个表如下:

tag表(只有英文标签):

ID    title
-------------
1     tag_1
2     tag_2
3     tag_3

tag_translation桌子:

ID    title      locale   tag_id (foreign key)
-----------------------------------------------
1     tag_1_fr   FR        1
2     tag_1_de   DE        1
3     tag_2_es   ES        3

如何进行 SQL 查询以法语返回所有标签,如果在法语中找不到标签,则回退到英语?

结果示例(选择法语的所有标签,回退到英语):

ID    title
---------------
1     tag_1_fr
2     tag_2
3     tag_3
4

3 回答 3

6
SELECT T.ID
       ,COALESCE(TT.TITLE, T.TITLE) AS TITLE
FROM tag T
LEFT JOIN tag_translation TT
    ON T.ID = TT.tag_id
    AND TT.locale = 'FR';

这假定 tag_id 和语言环境在 tag_translation 中是唯一的。

于 2013-06-26T17:04:53.973 回答
3

CASE用一个表达式试试这个:

SELECT
    T.ID,
    CASE
      WHEN TT.locale IS NOT NULL AND TT.locale = 'FR' THEN TT.title
      ELSE t.title
    END title
FROM tag T LEFT JOIN tag_translation TT ON T.ID = TT.tag_id
于 2013-06-26T16:49:12.987 回答
2

COALESCE应该得到你所追求的。

drop table if exists tag, tag_translation;

create table tag (
id int primary key,
title text
);

insert into tag values (1,'tag_1'), (2, 'tag_2'), (3, 'tag_3');

create table tag_translation (
id      int,
title   text,
locale  text,
tag_id  int references tag (id)
);

insert into tag_translation values
(1,'tag_1_fr', 'FR', 1),
(2,'tag_1_de', 'DE', 1),
(3,'tag_2_es', 'ES', 3);


select id, coalesce(fr.title, en.title) as title
from
(select id, title from tag) as en
left join (select id, title from tag_translation where locale = 'FR') as fr using (id)


 id |  title   
----+----------
  1 | tag_1_fr
  2 | tag_2
  3 | tag_3
于 2013-06-26T16:50:59.173 回答