这是一个有效的声明:
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
);
因此,如果table1包含(foo, bar)
对,而table2包含值(foo), (baz)
则不匹配。