一张表里有a ,b 两个字段,值是如下的情况,我要查询出b字段不同,a字段相同的数据,传进来的条件是b字段
a1,b1
a2,b1
a1,b2
a2,b2
我写的sql如下:select * from tab t1 where t1.a in(select t2.a from tab t2 where t2.b in ('b1','b2') group by t2.a having count(1)>1)
当传'b1','b2'这两个值的时候没有问题,但是我再传多一个'b3'进来,由于写法是用in的,得到的结果还是跟'b1','b2'查询的结果一样
怎么样才能传'b1','b2','b3'进来时,就查询不到数据了,因为表里根本都没有'b3'的数据,我要得到的是他们共同拥有的值

解决方案 »

  1.   

    你用的是IN 就算多加了一个B3 还是会和上面的是一样的结果的。再说你要的结果是“我要查询出b字段不同,a字段相同的数据” 和“怎么样才能传'b1','b2','b3'进来时,就查询不到数据了,因为表里根本都没有'b3'的数据,我要得到的是他们共同拥有的值 ” 怎么感觉矛盾啊
      

  2.   

    楼主应该把参数拿出来用and连接,in(1,2,3,4)的结果存在的数据都会拿出来
    select * from tab t1 
    where t1.a in(select t2.a from tab t2 where t2.b in ('b1') group by t2.a having count(1)>1)
    and t1.a in(select t2.a from tab t2 where t2.b in ('b2') group by t2.a having count(1)>1)
    and t1.a in(select t2.a from tab t2 where t2.b in ('b3') group by t2.a having count(1)>1)
      

  3.   

    select * from 
    (select * from tab t1 ,tab t2 where t1.a<>t2.a and t1.b=t2.b )where b=?
      

  4.   

    大概看了下,不知道是不是你想要的:
    表的数据如下:
    select * from a 
    a1 b2
    a1 b1
    a2 b3
    a2 b1
    a3 b2
    ---------------------------------------------------------------
    查询出b字段不同,a字段相同的数据
    select *
      from a
     where a.s1 in (select s1 from a group by s1 having count(s2) > 1)
    结果:
    1 a1 b2
    2 a1 b1
    3 a2 b3
    4 a2 b1
    -----------------------------------------------------------------
    查询出b字段不同,a字段相同的数据,传进来的条件是b字段
    select *
      from a
     where a.s1 in (select s1 from a group by s1 having count(s2) > 1)
          and s2 = 'b2'结果:
    1 a1 b2