仅当列为NULL时才加入

时间:2013-06-26 16:43:17

标签: sql postgresql join

我有两张表如下:

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

3 个答案:

答案 0 :(得分: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和locale在tag_translation中是唯一的。

答案 1 :(得分: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

答案 2 :(得分: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