如何在SQL查询语法中编写多列“ in”?

时间:2019-04-09 03:41:08

标签: sql sql-server

如何在SQL查询语法中写入多列?

示例:-

我要在表的所有3列(或所有3列中的任何一列)中查找名称:Peter:TableA

select * from TableA
where (colA, colB, colC) in 'Peter'

表具有数据透视格式的列。替代方法是..为语法中的每一列编写一个联合查询。

3 个答案:

答案 0 :(得分:9)

你能尝试

select * from TableA
where 'Peter' in (colA, colB, colC) 

答案 1 :(得分:4)

根据数据集的基数,这些列中的值等于“ Peter”,对于以下两种情况,效果可能相似或不同:

select * from TableA
where colA = 'Peter' OR colB = 'Peter' OR colC = 'Peter'

select *
from TableA
where colA = 'Peter'

union

select *
from TableA
where colB = 'Peter'

union

select *
from TableA
where colC = 'Peter'

但是,我的建议是使用UNION版本,因为在每列的“ Peter”基数较小的情况下,它可能会提供更好的性能。

答案 2 :(得分:2)

在您的情况下,这很理想,因为您正在寻找一个名字

select * from TableA
where colA='Peter' OR colB='Peter'OR colC='Peter'