带有多列的IN子句

时间:2014-07-27 20:53:01

标签: mysql sql

有没有办法使用只有一个查询使用带多个列的IN子句来实现以下联合查询?

而不是使用

select * 
from table_a 
where field_a in (select field_1 from table_b) 
union
select * 
from table_a 
where field_a in (select field_2 from table_b);

我想创建一些如下所示的内容:

select * 
from table_a 
where field_a in (select field_1,field_2 from table_b) ;

4 个答案:

答案 0 :(得分:5)

你能得到的最多就是将联合放在子查询中:

select * 
from table_a 
where field_a in (select field_1 from table_b union select field_2 from table_b)

或者:

select * 
from table_a 
where field_a in (select field_1 from table_b)
or field_a in ( select field_2 from table_b)

答案 1 :(得分:2)

相当于:

select *
  from table_a
 where field_a in (select field_1 from table_b)
    or field_a in (select field_2 from table_b)

不是这样:

select *
  from table_a
 where field_a in (select field_1, field_2 from table_b)

因为在后一种情况下,field1和field2必须出现在table_b的同一行上。

在您想要模仿的UNION查询中,情况并非如此。您需要2个单独的IN来模仿UNION查询正在执行的操作。

我不久前在这里回答了关于上述差异的类似问题:Difference in two SQL query, but same result

答案 2 :(得分:2)

select 
    * 
from 
    table_a a
where 
    exists(
        select 
            1 
        from 
            table_b b 
        where 
            a.field_a = b.field_1 OR 
            a.field_a = b.field_2
    )

答案 3 :(得分:2)

为什么不使用加入?然后,您可以列出in() ...

所需的所有列
select distinct
 a.* 
from table_a as a
    join table_b as b
    on a.field_a in (b.field_1, b.field_2)

或者,您可以利用exists()功能:

select distinct
 a.* 
from table_a as a
where exists (
    select
    *
    from table_b as b
    where a.field_a in (b.field_1, b.field_2)
)