多列的IN子句

3

有没有一种方法可以使用多列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个回答

5
最好的方法是将union放在子查询内部:
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)

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个单独的INs来模仿该UNION查询所做的操作。
我不久前回答了一个类似的问题,解释了上述两个SQL查询之间的区别:Difference in two SQL query, but same result

也许用 "或" 而不是 "和" 会更好? - daghan

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
    )

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

然而,如果在table_b中,由于未在问题中讨论的其他列而导致field_a值被列出多次,则会导致行重复。 - Brian DeMilia
@BrianDeMilia 嗯,我想我们可以应用一个distinct(考虑到他最初的联合实现,它本应该在那里),然后我们可以进行性能测试。我不经常处理特定的mysql...所以,我很想看看你的表现如何与我的相比。 - canon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接