SQL Left Join - 连接一个条件,默认为另一个条件

时间:2018-06-13 15:48:44

标签: sql oracle

我在两个表之间进行连接:

SELECT * FROM Thing thing
    LEFT OUTER JOIN ThingDetails details 
        ON (a.id = details.thing_id AND details.thing_language = 'Spanish')

这基本上会给我表中的所有条目' Thing'有西班牙语的详细信息 - 如果没有西班牙语的详细信息,它将给我空值。

我想做的是"后退"如果在西班牙语的ThingDetails中没有条目,即ON (a.id = details.thing_id AND details.thing_language = 'Spanish')失败,则为英语。

有没有办法轻松实现这个目标?基本上知道左连接的右侧是否为空?

2 个答案:

答案 0 :(得分:2)

你可以两次加入桌子。一次为您所需的语言,一次为您的默认语言。然后在您的选择中使用COALESCE()来执行默认操作:

SELECT thing.*, COALESCE(details_spanish.some_field, details_default.some_field) as some_field 
FROM Thing thing
    LEFT OUTER JOIN ThingDetails details_spanish
        ON (a.id = details.thing_id AND details.thing_language = 'Spanish')
    LEFT OUTER JOIN ThingDetails details_default 
        ON (a.id = details.thing_id AND details.thing_language = 'English')

答案 1 :(得分:1)

使用两个left join和`coalesce()

SELECT t.*,
       COALESCE(tds.col, tde.col) as as col
FROM Thing t LEFT JOIN
     ThingDetails tds 
     ON t.id = tds.thing_id AND tds.thing_language = 'Spanish' LEFT JOIN
     ThingDetails tde
     ON t.id = tde.thing_id AND tde.thing_language = 'English' AND tds.thing_id IS NULL;

LEFT JOIN将数据整合在一起。 COALESCE()选择您关注的列的适当值。如果您有更多关注的列,请添加更多COALESCE()行。

编辑:

如果您不想列出列,可以执行以下操作:

select t.*, td.*
from Thing t left joi
     (select td.*,
             row_number() over (partition by thing_id
                                order by case when td.thing_language = 'Spanish' then 1 else 2 end
                               ) as seqnum
      from ThingDetails td
      where thing_language in ('Spanish', 'English')
     ) td
where seqnum = 1;