Skip to content Skip to sidebar Skip to footer

Sql Query Help - Multiple Joins

having trouble with this SQL query. Here's the situation: I have three tables structured as follows: Events -> fields ID and Name, Players -> fields ID and Name, Matches -&

Solution 1:

Add a second JOIN to the Players table:

SELECT 
   Players.Name as Player1, Events.Name, 
   p2.Name as Player2
FROM 
   Matches 
INNER JOIN 
   Events ON Matches.EventID = Events.ID
INNER JOIN 
   Players ON Matches.Player1ID = Player.ID
INNER JOIN 
   Players p2 ON Matches.Player2ID = p2.ID;

Solution 2:

You can do this by joining the tables together. The trick is that you have to include the Players table twice. This is a case where you need table aliases to distinguish between these two references to the table in the from clause:

select m.matchid, e.name as event_name, p1.name as player1_name, p2.name as player2_name
from matches m join
     events e
     on m.eventid = e.id join
     players p1
     on m.player1 = p1.id join
     players p2
     on m.player2 = p2.id;

I also added table aliases for the other tables, which makes the query easier to read.

Solution 3:

SELECT p1.Name, p2.Name, Events.Name
FROMMatchesINNERJOIN Events ON (Matches.EventID=Events.ID))  
    INNERJOIN Players p1 ON (Matches.Player1ID = p1.ID)
    INNERJOIN Players p2 ON (Matches.Player2ID = p2.ID)

Solution 4:

You need to join the query again with the Players table on the Player2ID field. So change your query to:

SELECT one.Name as Player1, two.Name as Player2, Events.Name 
FROMMatchesINNERJOIN 
Events ON Matches.EventID=Events.ID INNERJOIN 
Players oneON Matches.Player1ID = one.ID INNERJOIN
Players two ON Matches.Player1ID = two.ID

Post a Comment for "Sql Query Help - Multiple Joins"