简体   繁体   中英

Single MySQL query on three tables

I have three tables as below:

Table 1: player_game

player_id | game_id
-------------------
    1     |    1
    2     |    2  
    5     |   20
    4     |    1
    2     |   20
-------------------

Table 2: players

player_id | player_name | player_age
------------------------------------
    1     |   John      |  20
    2     |   Abe       |  18
    5     |   Lisa      |  21
    4     |   Mary      |  25
    3     |   Romeo     |  21
------------------------------------

Table 3: games

game_id   | game_name    | diff_level
------------------------------------
    1     | AOE          |  easy
    2     | Contra       |  easy
   11     | Tribalwars   |  difficult
   20     | Tanks        |  novice
   25     | Minesweeper  |  medium
------------------------------------

I want to write a query that looks up the players and games table by using the IDs on the player_game table. The resulting table should give the player name and the corresponding games name. All the names of the players should be returned. If any player does not have an ID in the player_game table, it should list a NULL . Expected output is below:

Result:

Player Name |   Games Name
--------------------------
  John      |   AOE
  Abe       |   Contra
  Lisa      |   Tanks
  Mary      |   AOE
  Romeo     |   NULL
  Abe       |   Tanks
--------------------------

I have written the following query but its not working:

SELECT p.player_name AS "Player Name", g.game_name AS "Games Name"
FROM players p
LEFT OUTER JOIN player_game pg
ON p.player_id = pg.player_id
JOIN games g
ON g.game_id = pg.game_id;

Please advise what am I doing wrong.

Your answer looks good except your 2nd join. Your 2nd join should also be left(outer) join otherwise you won't be seeing "Romeo NULL" record.

Other than this, Abe has 2 games linked( Contra and Tanks) as it is already mentioned. You expect to see both of them in your output? If so, your code will do it. If you want Abe to have only one game linked, then you need to tell us the logic for selecting the one of the games.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM