Question

Update years later:

I came back to answer my own question. I had no idea what an inner join was and apparently completely misused the term here.


I currently have the following 3 tables:

Team

TeamID

Player

PlayerID | TeamID

Match

Player1 | Player2 | Round

I want to write a query showing a match like:

Team1 | Team2

I figured out how to join my tables player and match, so far that works too, but I can't figure out how to replace the player name with the team name. Any idea? I have the following:

SELECT P1.PlayerID AS Player1, P2.PlayerID AS Player2
FROM MATCH
INNER JOIN PLAYER AS P1 ON MATCH.Player1 = P1.PlayerID
INNER JOIN PLAYER AS P2 ON MATCH.Player2 = P2.PlayerID
Was it helpful?

Solution

I've come back to this question years later.

Assuming the following tables:

Team

id | name

Player

id | team_id

Match

player1_id | player2_id | round

The result I wanted was something like

player1's team name | player2's team name | round

I used distinct originally, but distinct is not the correct way to remove duplicates, as Turophile correctly points out.

A better query would be something like

select t1.name, t2.name, m.round
from match as m
left join player as p1 on m.player1_id = p1.id
left join team as t1 on p1.team_id = t1.id
left join player as p2 on m.player2_id = p2.id
left join team as t2 on p2.team_id = t2.id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top