多对多关系查询-mySQL

时间:2018-10-18 18:13:15

标签: php mysql sql join

我有以下表格,表格A和表格B

表A(用户)

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

表B(爱好列表)

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

我有一个桥接表(许多关系)

表C(user_hobby)

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

我想查询一个条件,我想知道哪个用户的爱好等于“绘画”(爱好2),而不是“唱歌”(爱好1)。 如何在没有子查询的情况下实现这一目标

我尝试了以下查询

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"

由于上述查询,我​​仍然同时拥有两个用户。它应该只显示用户= David。

如何在不使用子查询的情况下实现此目标

3 个答案:

答案 0 :(得分:0)

  • 您可以Group by输入用户名和名称。这样会将结果汇总到特定用户的单行中。
  • 现在,我们可以将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 

答案 1 :(得分:0)

您可以使用group byhaving

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表。

答案 2 :(得分:0)

尝试使用内部联接:

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"