I’m having trouble coming up with a working query for this situation…
Table:
[ matchID ] [ User ] [ team ]
1 10 1
1 77 2
2 10 1
2 77 1
3 10 2
4 10 1
Notes:
- sometimes the opponent is unknown, for example in matches 2, 3, and 4
- sometimes a team has only one person on a side, for example match 1
- sometimes a team has n persons on a side, for example match 2
Desired Query Results:
A list of matchIDs for a given user where the opponent is unknown.
My first attempt was:
SELECT matchID FROM table
GROUP BY matchID
HAVING COUNT(matchID) = 1
but then I realized that I wasn’t counting matches where there are teammates but unknown opponents, such as match 2 above.
In plain English, I need to get all matchIDs where:
- involving a given user <- edited to add
- everyone is on the same team
- OR there is only one person listed
but I’m not sure how to do that efficiently in one query. Help?
You seem to need those matches where only one team is recorded in the table, and this query gives you those matches.
If the match must involve a specific user (10 for the sample data), then:
You can probably do that as an (inner) self-join:
Or, perhaps a little more clearly:
The sub-select picks those matches where UserID 10 played; the rest works as before.