有A表,结构为:uid 和 uname 两个字段 (比如用户表)
有B表,结构为:aid 和 aname 两个字段  (比如爱好表)有A,B的关联表C (比如一个用户有N个爱好),结构 uid 和aid现在想从C表中查询
1:只有aid 为 1 和 2 这两个爱好的用户有哪些 (即必须只有这两个爱好的用户)2:包含aid 1和2这个两个爱好的用户有哪些,(即必须要>=这个两个爱好的用户)
一时没想出来,还请高手帮忙!

解决方案 »

  1.   

    1:只有aid 为 1 和 2 这两个爱好的用户有哪些 (即必须只有这两个爱好的用户)
    ==>
    select a.*
    from c cc join a on cc.uid=a.uid 
    where exists(select * from c where c.uid=uid and aid=1)
    and  exists(select * from c where c.uid=uid and aid=2)
    and not exists(select * from c where c.uid=uid and (aid<>1 or aid<>2))2:包含aid 1和2这个两个爱好的用户有哪些,(即必须要>=这个两个爱好的用户)
    ====>
    select a.*
    from c cc join a on cc.uid=a.uid 
    where exists(select * from c where c.uid=uid and aid=1)
    and  exists(select * from c where c.uid=uid and aid=2)
      

  2.   

    1:只有aid 为 1 和 2 这两个爱好的用户有哪些 (即必须只有这两个爱好的用户)
    select c1.uid
    from c c1 inner join c c2 on c1.uid=c2.uid
    where c1.aid=1 and c2.aid=2
    and not exists (
    select 1 from c
    where uid=c1.uid 
    and aid !=1 and aid !=2
    )
      

  3.   

    2:包含aid 1和2这个两个爱好的用户有哪些,(即必须要>=这个两个爱好的用户)
    select c1.uid
    from c c1 inner join c c2 on c1.uid=c2.uid
    where c1.aid=1 and c2.aid=2