如表: id        商品id             商品属性       属性内容
            id     productId             attr           content
            1              1                    颜色             红色
            2              1                    长度             10厘米
            3              1                    宽度              20厘米
            4              2                    颜色              红色
            4              2                    长度              20厘米
我就想从这个表中找出  颜色为红色,长度为10厘米   的商品的id             结果应该是 1 
请问各位查询语句怎么写呢?  在线等!

解决方案 »

  1.   

    select productId
    from attr='红色' and attr='10厘米'
    group by productId
      

  2.   

    select productId
    from 如表 a , 如表 b
    where a.productId=b.productId
    and a.attr='颜色' and a.content='红色'
    and b.attr='长度' and b.content='10厘米'
      

  3.   

    select productId
    from tb
    where attr='颜色' and  content='红色'
    and  attr='长度' and  content='10厘米'
    group by productId
    having (distinct attr)>1
      

  4.   

    select productId
    from tb
    where (attr='颜色' and content='红色')
    or (attr='长度' and content='10厘米')
    group by productId
    having (distinct attr)>1
      

  5.   

    select productId
    from tb
    where (attr='颜色' and content='红色')
    or (attr='长度' and content='10厘米')
    group by productId
    having (count(*))>1
      

  6.   

    如果 条件再加上  宽度为20厘米,那估计就不行了,实际的需求是条件的数量不定select distcint productId
    from 如表 a 
    where exists (select 1 from 如表 where productId=a.productId and attr='颜色' and content='红色')
    and exists (select 1 from 如表 where productId=a.productId and attr='长度' and content='10厘米')
    and exists (select 1 from 如表 where productId=a.productId and attr='宽度' and content='20厘米')
      

  7.   

    如果你能确保 ( 商品id , 商品属性)唯一性。则可以select productId
    from 如表
    where (attr='颜色' and content='红色')
    or (attr='长度' and content='10厘米')
    or (attr='宽度' and content='20厘米')
    group by productId
    having count(*)=3