I'm not entirely sure how to phrase this as a concise question title.
I have a games
table which contains of records representing games of a player against another. The relevant columns of this table are userid1
and userid2
. I have another table called accounts
, consisting of the columns id
and username
.
I'd like to fetch the username of the opponent from the accounts
table. The opponent is the user of which the id is not equal to the known user id. So, if userid1 = 123
then I'd like to fetch accounts.username
of the user where accounts.id
is equal to userid2
of the same games
record. The same goes the other way round if userid2 = 123
.
I've so far only been able to select the opponent's username separately using two queries:
SELECT * FROM games, accounts
WHERE games.userid1 = 123 AND accounts.id = games.userid2
and:
SELECT * FROM games, accounts
WHERE games.userid2 = 123 AND accounts.id = games.userid1
(swapped: ^ ^)
However, I'd like to combine these two queries nicely into one. So, is it possible to get accounts.username
where accounts.id
is equal to:
games.userid2
ifgames.userid1
is equal to the known user idgames.userid1
ifgames.userid2
is equal to the known user id
and if so, how?