mysql 多对多 过滤,使用多对多表MySQL进行过滤

博客探讨如何使用SQL从people_to_sports表中筛选出同时参与特定两项运动(例如棒球和足球)的所有人员。通过提供SQLfiddle链接,展示了利用IN和GROUP BY子句以及HAVING COUNT(*)条件来实现这一目标的查询方法。
摘要由CSDN通过智能技术生成

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!

解决方案SELECT

personID

FROM

people_to_sports

WHERE

sportID IN (1, 2)

GROUP BY

personID

HAVING

COUNT(*) = 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值