SQL一起使用OR和IN

时间:2018-03-07 16:29:15

标签: sql-server

我试图用IN子句选择多个OR子句。以下是我的表达:

Select * from ABC
Where XYZ OR CDP OR Bell in (TermYard1,TermYard2,TermYard3,TermYard4)

我也试过

Select * from ABC
Where('XYZ','CDP','Bell') in (TermYard1,TermYard2,TermYard3,TermYard4)

感谢您提供的任何帮助

6 个答案:

答案 0 :(得分:2)

试试这个:

SELECT * FROM ABC
WHERE
XYZ IN (TermYard1,TermYard2,TermYard3,TermYard4) OR
CDP IN (TermYard1,TermYard2,TermYard3,TermYard4) OR
Bell IN (TermYard1,TermYard2,TermYard3,TermYard4)

答案 1 :(得分:2)

Another option使用内存表

with q as (
  select 'XYZ' as Term
  union all select 'CDP'
  union all select 'BELL'  
)
select distinct ABC.* 
from   ABC
       inner join q on Term in (TermYard1, TermYard2, TermYard3, TermYard4)

向Joel致敬,以进一步简化此
向Paparazzi致敬,修复多行

答案 2 :(得分:1)

这有多个术语匹配将重复行的问题 select distinct会修复

select abc.* 
  from ( values ('XYZ'), ('CDP'), ('Bell')
       ) term(t)    
   join abc 
     on term.t in (TermYard1, TermYard2, TermYard3, TermYard4)  

答案 3 :(得分:0)

如果你不介意将同一个清单放三次......

Select * from ABC
Where XYZ  in (TermYard1,TermYard2,TermYard3,TermYard4)
 OR CDP  in (TermYard1,TermYard2,TermYard3,TermYard4)
 OR Bell in (TermYard1,TermYard2,TermYard3,TermYard4)

答案 4 :(得分:0)

你做不到。

假设XYZ和CDP和Bell是表(或视图)ABC的字段,您可以写:

Select * from ABC
Where XYZ in (TermYard1,TermYard2,TermYard3,TermYard4) OR 
      CDP in (TermYard1,TermYard2,TermYard3,TermYard4) OR 
      Bell in (TermYard1,TermYard2,TermYard3,TermYard4);

答案 5 :(得分:0)

要做到这一点,你有两个选择:

对要过滤的每列重复IN列表项:

Select 
    * 
from 
    ABC
Where
    XYZ in (TermYard1,TermYard2,TermYard3,TermYard4) OR
    CDP in (TermYard1,TermYard2,TermYard3,TermYard4) OR
    Bell in (TermYard1,TermYard2,TermYard3,TermYard4)

创建一个包含IN值的表格,并使用多个EXISTS执行OR

IF OBJECT_ID('tempdb..#YardTerms') IS NOT NULL
    DROP TABLE #YardTerms

CREATE TABLE #YardTerms (Term VARCHAR(100))

INSERT INTO #YardTerms (Term)
VALUES
    ('TermYard1'),
    ('TermYard2'),
    ('TermYard3')

Select 
    * 
from 
    ABC
WHERE 
    EXISTS (SELECT 1 FROM #YardTerms WHERE XYZ = Term OR CDP = Term OR Bell = Term)