日期:2014-05-18  浏览次数:20581 次

sql的where的一个条件属于一个集合 该怎么写?
我在构建where子句的时候 对其中一个字段允许有多个值 该怎么写这个句子呢?
具体情况是 a 的可用值是1,2,3,4 用户可以选择多个值
比如用户选了 1,3,4
我现在的where子句要检索出a=1或者a=3或者a=4且a!=2的所有结果
注意where子句除了条件a 还有其他条件b,c,d....
这个句子应该怎么写好?

------解决方案--------------------
where a in(1,2,3,4)
------解决方案--------------------
SQL code

declare @str varchar(20)
set @str='1,2,3,4'
select * from tbl where charindex(','+ltrim(a),','+@str)>0

------解决方案--------------------
where a in(1,2,3,4) and b='anything' and c=……
------解决方案--------------------
探讨
我在构建where子句的时候 对其中一个字段允许有多个值 该怎么写这个句子呢?
具体情况是 a 的可用值是1,2,3,4 用户可以选择多个值
比如用户选了 1,3,4
我现在的where子句要检索出a=1或者a=3或者a=4且a!=2的所有结果
注意where子句除了条件a 还有其他条件b,c,d....
这个句子应该怎么写好?

------解决方案--------------------
用in来实现嘛,相当于是要查的变量的集合 where ?? in(1,2,3)
------解决方案--------------------
where a in( select a=1 union select 2 union select 3)
and a not in( select a=4 union select 5 union select 6)
and b....
and c....