IN条件左侧的多列

时间:2019-02-20 07:55:30

标签: sql postgresql sql-in

这是有效的声明:

SELECT foo FROM table1 WHERE
  column1 IN (SELECT bar FROM table2) AND
  column2 IN (SELECT bar FROM table2)

但是有什么方法可以避免重复执行SELECT bar FROM table2语句以使其更简单,更经济?

我的意思是这样的:

SELECT foo FROM table1 WHERE
  «column1 and also column2» IN (SELECT bar FROM table2)

2 个答案:

答案 0 :(得分:4)

您可以与EXISTS运算符一起使用相关的子查询

select *
from table1 t1
where exists (select *
              from table2 t2
              where t2.bar in (t1.column1, t1.column2));

如果两列都应与table2.bar中的值匹配,则可以使用以下内容:

select *
from table1 t1
where exists (select *
              from table2 t2
              where t2.bar = t1.column1
                and t2.bar = t1.column2);

答案 1 :(得分:3)

您可以使用聚合:

select *
from table1
where exists (
    select 1
    from table2
    where table2.bar in (table1.column1, table1.column2)
    having count(distinct bar) = case when table1.column1 = table1.column2 then 1 else 2 end
);

因此,如果table1包含对(foo, bar),而table2包含值(foo), (baz),则 不会 匹配。