tags:

views:

26

answers:

1

In a situation where I have two tables:

  • Games(id, player1Id, player2Id)
  • Players(id, gender)

And I would like to select all of the games and the player's gender, how would I get around null playerIds?

From this explanation, I would think the answer would be:

SELECT Games.id, p1.gender, p2.gender
FROM Games JOIN Players p1 on player1Id = p1.id 
JOIN Players p2 on player2Id = p2.id

However, this does not return any game that has either player1Id or player2Id as null. Is there a way to show all games with players connected when possible?

Thanks.

+5  A: 

You need to use a LEFT JOIN:

   SELECT g.id, p1.gender, p2.gender
     FROM Games g
LEFT JOIN Players p1 ON p1.id = g.player1Id
LEFT JOIN Players p2 on p2.id = g.player2Id

Here's a really good link that visual demonstrates the different JOINs

OMG Ponies
Thanks and great article. The only thing I had left to google was the difference between LEFT JOIN and LEFT OUTER/INNER JOIN to find that OUTER is default. Thanks again.
mphair
@mphair: Yeah, I find the "OUTER" part to be verbose myself. What database is this for?
OMG Ponies
@OMG Ponies: Nothing in particular, just made up the tables to fit the question. Special curiosity-driven-database, I guess. =P
mphair