Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter using a many-to-many table MySQL

Tags:

sql

mysql

filter

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. I am using php to allow a user to see a list of people. 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?

I have a sqlfiddle here.

Thank you!

like image 583
ajon Avatar asked Dec 18 '25 03:12

ajon


2 Answers

SELECT
  personID
FROM
  people_to_sports
WHERE
  sportID IN (1, 2)
GROUP BY
  personID
HAVING
  COUNT(*) = 2
like image 162
MatBailie Avatar answered Dec 20 '25 16:12

MatBailie


SELECT personID, COUNT(personID) AS cnt
FROM people_to_sports
WHERE sportID IN (1, 2)
GROUP BY personID
HAVING cnt = 2
like image 36
Marc B Avatar answered Dec 20 '25 15:12

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!