0

I am getting a bit confused with this basic SQL question, I was hoping you could give me a hint about what am I doing wrong:

I have a main table with different players:

id  | name
----+-----
1   | John
2   | Paul
3   | Robert

And another table that stores their matches

date      |  player_home  |  player_away
----------+---------------+-------------
2012-03-21|  1            |  2
2012-04-10|  2            |  3

I am trying to build a query that outputs the names of both players for a given date, but the name of the same player is being repeated in both fields:

This retrieves nothing:

SELECT date, player_home, name, player_away, name 
FROM games, players 
WHERE date = (DATE '2012-03-21') 
AND games.player_home = players.id 
AND games.player_away = players.id;

And if I remove the second AND, it retrieves the same name (John) for both players:

date      |  player_home  |  name   |   player_away  |   name
----------+---------------+---------+----------------+-------
2012-03-21|  1            |  John   |   2            |   John 

When the name in the second "name" field should be "Paul".

What is the right way to build this query?

Thanks in advance

2 Answers 2

1

You need to join the players table twice and use different alias names for the tables

SELECT g.date, p1.name as home_name, p2.name as away_name
FROM games g
JOIN players p1 ON g.player_home = p1.id 
JOIN players p2 ON g.player_away = p2.id 
WHERE g.date = (DATE '2012-03-21') 
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, I was guessing it had to be something with join... I also didn't know about the alias thing. Useful to know!
1
SELECT date, player_home, players_home.name, player_away, player_away.name 
FROM games
left outer join players players_home on player_home=players.id
left outer join players players_away on player_away=players.id
WHERE date = (DATE '2012-03-21') ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.