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

解决方案 »

  1.   

    可不可以试试不就知道了,你这种可以用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
      

  2.   

    写两次吧,不写两次还真不好实现,你上面贴出的用case的方法好像不行哦
      

  3.   

    select *  from  student  where  A= A   and B=B  and username = (select   case when age !=1 then 'a'    else username    end  from dual )  改成这样
      

  4.   


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

  5.   

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

  6.   

    为什么认为这种写法bug太多,不安全呢?
    用decode更简洁些
      

  7.   

    age 为空的情况。另外万一,这个student 表和其他表有关联的时候。。都会有问题
      

  8.   

    我是这样写的:
    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';