如果要查询同一列满足两个条件
比如  
ID 属性
1  a
1  b
2  c
3  d
要求查询属性同时是a 和 b的ID 查出来只有1  

解决方案 »

  1.   

    SELECT DISTINCT ID FROM tbName  WHERE [属性] IN('a','b')
      

  2.   

    1楼的可以了嘛,你要怎么的?难道是下面的?SELECT ID FROM tbName  WHERE [属性]='a'
    UNION
    SELECT ID FROM tbName  WHERE [属性]='b'
      

  3.   


    ;with cte(id,pro) as
    (
    select 1,'a'
    union all select 1,'b'
    union all select 2,'c'
    union all select 3,'d'
    )
    select ID
    from cte a
    where pro='a' and exists(select 1 from cte b where pro='b' and a.id=b.id)/*
    ID
    1
    */
      

  4.   

    是我没说清楚
    比如说
    ID  属性
    1  a
    1  b
    2  a
    2  a
    3  b
    3  b
    查询要求属性列有a和b的ID ,查询出来只有1
    我用 select id,属性 from 表 group by ID,属性 having 属性in(a,b) and count(*)=2
    这样还是会把 2和3 带进去 
      

  5.   


    ;with cte(id,pro) as
    (
    select 1,'a'
    union all select 1,'b'
    union all select 2,'c'
    union all select 3,'d'
    )select a.id from 
    (
    select * from cte where pro='a'
    )a
    left join 
    (select * from cte where pro='b')b
    on a.id=b.id
    ------------------------------------
    id
    -----------
    1(1 行受影响)
      

  6.   

    45678910111213141516 ;with cte(id,pro) as( select 1,'a'union all select 1,'b'union all select 2,'c'union all select 3,'d')  这一段我看不懂,这是用表里的源数据来重新做个表么?这样不是本末倒置么?
      

  7.   

    ;with cte(id,pro) as
    (
    select 1,'a'
    union all select 1,'b'
    union all select 2,'c'
    union all select 3,'d'
    )
    , cte1
    as
    (
    select * from cte  where pro='a'
    union all
    select * from  cte where pro='b'
    )
    select distinct id from cte1
      

  8.   

    select discinct id from table as t1 inner join table as t2 
    on t1.id=t2.id where t1.name='a' and t2.name='b'
      

  9.   


    看来你的数据量不小啊,其实要加快语句的运行速度,不仅在与sql语句的写法,也需要建索引,
    这里的语句,大致上也就是这么写了:
    SELECT ID FROM tbName  WHERE [属性]='a'
    UNION
    SELECT ID FROM tbName  WHERE [属性]='b'为了加快查询速度,不管你的数据量达到是1000w条,还是1亿条,都没有问题,只要建个索引,就能把性能提升百倍:
    create index idx_index_name on tbName([属性],ID)