多对多关系查询-mysql

bq3bfh9z  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(377)

我有下表,表a和表b
表a(用户)

userid    name
--------------------
1         Sam
2         David

表b(hobbylist)

hobbyid   hobby
--------------------
1         singing
2         drawing

我有一个桥牌(多对多关系)
表c(用户爱好)

userid    hobbyid
--------------------
1         1
2         2
1         2

我想查询一个条件,在这个条件下,我想知道哪个用户的爱好等于“画画”(hobbyid2),而不是“唱歌”(hobbyid1)。如何在没有子查询的情况下实现这一点?
我尝试了以下查询

SELECT * 
FROM hobbylist 
     JOIN user_hobby AS uh 
       ON hobbylist.hobbyid = uh.hobbyid
     JOIN users AS us 
       ON us.userid = uh.userid
WHERE hobby = "drawing" 
  AND hobby <> "singing"

作为上述查询的结果,我仍然得到这两个用户。它应该只显示user=david。
如何在不使用子查询的情况下实现这一点?

klsxnrf1

klsxnrf11#

你可以用 group by 以及 having :

select uh.userid
from user_hobby uh join
     hobby h
     on h.hobbyid = uh.hobbyid
where h.hobby in ('drawing', 'singing')
group by uh.userid
having min(h.hobby) = max(h.hobby) and min(h.hobby) = 'drawing';

请注意,要获得 userid ,您不需要users表。

ctehm74n

ctehm74n2#

你可以 Group by 在userid和name上。这会将结果聚合到特定用户的单行中。
现在,我们可以使用 HavingSum() 把箱子过滤掉。 Sum(hobby = 'drawing') 对于有绘画爱好的用户将是积极的。 Sum(hobby = 'singing') 对于没有唱歌作为爱好的用户来说将是零。
请尝试以下操作:

SELECT us.userid,
       us.name
FROM   hobbylist
       JOIN user_hobby AS uh
         ON hobbylist.hobbyid = uh.hobbyid
       JOIN users AS us
         ON us.userid = uh.userid
GROUP  BY us.userid,
          us.name
HAVING Sum(hobby = 'drawing')
       AND Sum(hobby = 'singing') = 0
ryoqjall

ryoqjall3#

尝试以下innerjoin:

select * from hobbylist, user_hobby, users where users.userid = user_hobby.userid and hobbylist.hobbyid = user_hobby.hobbyid and hobbylist.hobby = "drawing" and hobbylist.hobby <> "singing"

相关问题