문제

I have an M2M relation on two tables in an SQL database, as follows:

Players
-------
Name
ID

Teams
------
Name
ID

PlayersTeams
------
PlayerID
TeamID

A team consists of 1 or more players.

I would like to query for a team given its player IDs, and return only the team that contains exactly those players, no more, no less. So querying for a team with players (1,2,3) would only return team with players 1,2,3, and not a team with players 1,2,3,4.

Is this possible in a single query?

I've got an sqlfiddle I'm trying to work it out in here: http://sqlfiddle.com/#!2/27799/8

in that example i'd like to be able to select the team "john and mick" by querying with player IDs 1 and 2...

update in this sqlfiddle http://sqlfiddle.com/#!2/27799/69 I can select the team ID 2 ("john and mick") but it also gets team ID 4 ("john, mick and trev"). Need to filter it down to JUST 2.

도움이 되었습니까?

해결책

select  TeamId
from    PlayersTeams
group by TeamId 
having count(*) = sum(case when playerid in (1,2) then 1 else 0 end) 
 and count(*) = 2

Not familiar with mysql so I don;t know how to get the players list length (the count(*) =2) to make is fully dynamic but you get the point.

다른 팁

I added player 3 in team 3 to create all possible cases. This is my answer:

SELECT t.*

FROM playersteams a,

     teams t

WHERE a.teamid = t.id

AND (SELECT COUNT(*) FROM playersteams c
     WHERE c.teamid = a.teamid
     AND c.playerid = 2) = 1

AND (SELECT COUNT(*) FROM playersteams c
     WHERE c.teamid = a.teamid
     AND c.playerid = 3) = 1

GROUP BY t.id, t.name

HAVING COUNT(a.playerid) = (SELECT COUNT(*) FROM players WHERE id IN (2,3));

SQL Fiddle: demo

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top