我有events
表,如下所示
id name
1 Ind Vs Pak
2 Fedrer Vs Nadal
3 MI Vs RR
event_participations
id participant_type participant_id event_id
1 Team 1 1
2 Team 2 1
3 Athlete 1 1
4 Athlete 2 1
5 Athlete 3 1
6 Athlete 4 2
7 Athlete 5 2
8 Team 3 3
9 Team 4 3
10 Athlete 6 3
11 Athlete 7 3
12 Athlete 8 3
我希望所有至少有一个Team
的活动如下
id name
1 Ind Vs Pak
3 MI Vs RR
答案 0 :(得分:1)
SELECT e.id, e.name FROM events e
JOIN event_participations ep ON ep.event_id = e.id
WHERE ep.participant_type = 'Team'
GROUP BY e.id
HAVING COUNT(e.id) > 1;
将输出显示为
| ID | NAME |
-|----|------------|-
| 1 | Ind Vs Pak |
| 3 | MI Vs RR |
答案 1 :(得分:0)
你应该使用“拥有”。试试这个:
select e.* from events e join event_participations ep on ep.event_id = e.id where ep.participant_type = 'Team' group by e.* having count(*) > 1
更新:我认为你的意思不止一个。如果您只需要至少一个
,则应该进行简单的连接答案 2 :(得分:0)
SELECT * FROM events AS e
LEFT JOIN event_participants AS ep
ON (e.id = ep.event_id)
WHERE ep.participant_type = 'team'
GROUP BY ep.event_id
HAVING COUNT(ep.event_id) > 1
sqlfiddle demo:http://sqlfiddle.com/#!2/09ae7/6