IN 条件左侧的多列

Multiple columns on left side of IN condition

这是一个有效的声明:

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)

您可以使用带有 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);

您可以使用聚合:

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
);

所以如果表 1 包含对 (foo, bar) 并且表 2 包含值 (foo), (baz) 将不会 匹配.