有这么一个表,存储着两个对象;
id     key    value
1       a      11
1       b      22
1       c      33
2       a      11
2       c      33
2       d      44我想查询出某几个属性值与对象1相同的对象的个数。这里的对象1 (a=11,b=22,c=33),对象2(a=11,c=33,d=44),如果属性为a,c的话,结果显然应该是1。Sql怎么写?下面是我错误的代码:
select count(b.id)
from table a, table b
where a.key=b.key
and a.value=b.value
and b.id<>1
and a.key in (select key from table where another_rule); -- 相当于in('a','c')这里select key from table where another_rule就是为了查询出a,c,这两个属性也是动态的。
这个代码肯定错了,它的结果会是2,我知道错误原因,现在求正确的sql。

解决方案 »

  1.   

    把count(b.id)改为count(distinct b.id)试试
      

  2.   

    and a.key in (select key from table where another_rule); 
    --AND A.KEY = 'A'
    --AND A.KEY = 'C'
    不知是不是这样
      

  3.   

    谢谢两位的回答!
    To duanzilin: 不可以,上面的sql错误在于select key from table where another_rule,必须保证这个结果集中的n个属性的值同时相等,这个句法的实际意思却是结果集中的n个属性的值中任意一个相等即可。To sduzjw:您看出问题了,但是这个A,C都是查出来得,sql写的时候,不知道查询结果,所以AND A.KEY = 'A'...不可能写的
      

  4.   

    由于表结构不够合理只能采用这样的低效率查询:select id from(
    select distinct t1.id,t1.key from a t1
    where exists(select * from a where key in('a','c') and id=1 and key=t1.key)) group by id having count(id)>1
      

  5.   

    应该是:select id from(
    select distinct t1.id,t1.key from a t1
    where exists(select * from a where key in('a','c') and id=1 and key=t1.key)) 
    group by id having count(id)=(select count(*) from (select distinct id,key from a where key in('a','c') and id=1))
      

  6.   

    改进后的做法:select t1.id from a t1
    where not exists (
    select * from a t2 where t2.id=1 and t2.key in('a','c') and not exists(
    select * from a t3 where 
    t3.id=t1.id  and t3.key=t2.key and t2.key<>t1.key))