日期:2014-05-17  浏览次数:20883 次

在线等...where中的case when .. 求高手..急




select 
 * 
from 
  student 
 where 
  .....此处有多个检索条件,假设为以下。。
   A = A 
  and B=B 
  and 
  -----我想在此处实现,当满足条件年龄!= 1 的时候 添加一个检索条件 username = 'a'



不知各位看懂没有。。

就是当年龄!= 1得时候
检索条件为
    A = A 
  and B=B 
   and 
  username = 'a'

就是当年龄= 1得时候
检索条件为
    A = A 
  and B=B 


目前这种写法可否????


select 
 * 
from 
 student 
where 
 A= A 
 and B=B
 and username = 
  case when age !=1 then 'a'
    else username 
  end

  

还有一种方法就是写两次条件。。。。这种太麻烦了。。


求高手赐简单写法。。
急急。。。上午12点之前就要。。
sql

------解决方案--------------------
可不可以试试不就知道了,你这种可以用union的
select *
  from student p
 where p.age <> 1
   and A = A
   and B = B
   and username = 'a'
union
select *
  from student q
 where p.age = 1
   and A = A
   and B = B
------解决方案--------------------
写两次吧,不写两次还真不好实现,你上面贴出的用case的方法好像不行哦
------解决方案--------------------
我试了下,可以的 
------解决方案--------------------
select *  from  student  where  A= A   and B=B  and username = (select   case when age !=1 then 'a'    else username    end  from dual )  改成这样

------解决方案--------------------




 
select 
 * 
from 
 student 
where 
 A= A 
 and B=B
 and username = decode(age,1,username,'a')

------解决方案--------------------
为什么认为这种写法bug太多,不安全呢?
用decode更简洁些
引用:
引用:我试了下,可以的

那种写法 bug太多了...不安全..

------解决方案--------------------
我是这样写的:
SELECT 
*
from
student  
case 
when age = 1 then
A=A
and B=B 
when age <> 1 then
A=A
and B=B 
and username = 'a';