根据特定条件从表中选择“描述”

时间:2020-01-15 12:36:08

标签: sql database postgresql

我有两个表:

表1

**column0**       **description**
foo               this
bar               that
hello             yellow
bye               sky
...
baz               fred

table2

**column1**       **column2**
foo
bar               hello
...
baz               bye

Column0在column1和column2中都有所有内容

我要根据以下条件从表1中选择描述:

1)如果column2为空,则选择描述,其中column1 = column0。

2)否则,显示描述,其中column2 = column0

请让我知道是否需要任何澄清。我正在尝试在Postgresql中做到这一点。

****************更新****************:

根据您从表格中看到的信息得出的结果将是

  1. 'foo'的描述为'this',因为column2在'foo'旁边为空

  2. 'hello'的说明,因为它在column2中不为空

  3. “再见”的说明,因为在第2列中该字段不为空

因此:

this

yellow

sky

3 个答案:

答案 0 :(得分:0)

您需要连接表并在COALESCE()子句中使用ON,如下所示:

select t1.description
from table2 t2 inner join table1 t1
on coalesce(t2.column2, t2.column1) = t1.column0

您可能还需要一个ORDER BY子句才能按所需顺序获得结果。
请参见demo
结果:

| description |
| ----------- |
| sky         |
| this        |
| yellow      |

答案 1 :(得分:0)

尝试一下:

select test from(
select case when t2.column2 is null then t1.description
            else null
      end test
from table1 t1
left join table2 t2
on t1.column0 = t2.column1) A
where test is not null;

这里是DEMO

答案 2 :(得分:0)

我认为exists可能就足够了:

select t1.description
from table1 t1
where exists (select 1
              from table2 t2
              where t2.column1 = t1.column0
             ) or
      exists (select 1
              from table2 t2
              where t2.column2 = t1.column0
             );

也就是说,您的特定规则似乎是:

select t1.description
from table1 t1 left join
     table2 t2
     on t2.column1 = t1.column0 and
        t2.column2 is null left join
     table2 tt2
     on tt2.column2 = t1.column0 and
        t2.column1 is null
where t2.column1 is not null or
      tt2.column2 is not null;