简体   繁体   English

使用多对多表MySQL进行过滤

[英]Filter using a many-to-many table MySQL

I have the following tables (other tables ommitted for simplicity). 我有以下表格(为简单起见,省略了其他表格)。 1 is for all of the people, 2 is for the sports that those people play. 1代表所有人,2代表那些人玩的运动。 I am using php to allow a user to see a list of people. 我使用PHP来允许用户查看人员列表。 They can filter by a person's name, or by the sports they play. 他们可以根据一个人的名字或他们玩的运动来过滤。 So, I want the ability to see all people that play for example baseball and football. 所以,我希望能够看到所有玩棒球和足球的人。

create table people (
  id int,
  name varchar(50)
  );

create table people_to_sports (
  personID int,
  sportID int,
  primary key(personID,sportID)
  );

Basically my question is, how can I use people_to_sports to get a list of all people that play sport 1 and sport 2 for example? 基本上我的问题是,我如何使用people_to_sports来获取所有参加运动1和运动2的人的列表?

I have a sqlfiddle here . 这里有一个sqlfiddle。

Thank you! 谢谢!

SELECT
  personID
FROM
  people_to_sports
WHERE
  sportID IN (1, 2)
GROUP BY
  personID
HAVING
  COUNT(*) = 2
SELECT personID, COUNT(personID) AS cnt
FROM people_to_sports
WHERE sportID IN (1, 2)
GROUP BY personID
HAVING cnt = 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM