简体   繁体   中英

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 -> fields ID, EventID, Player1ID, Player2ID

I would like to perform a query that shows me the Matches Table, but replaces the EventID with the Event.Name, the Player1ID with the Players.Name and the Player2ID with the Players.Name.

It is easy for me to get one Player and the Event using this:

SELECT 
   Players.Name as Player1, Events.Name 
FROM 
   (Matches 
INNER JOIN 
   Events ON (Matches.EventID=Events.ID))  
INNER JOIN 
   Players ON (Matches.Player1ID = Player.ID) ;

But, how do I get the Player2's name?

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;

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.

SELECT p1.Name, p2.Name, Events.Name
FROM Matches
    INNER JOIN Events ON (Matches.EventID=Events.ID))  
    INNER JOIN Players p1 ON (Matches.Player1ID = p1.ID)
    INNER JOIN Players p2 ON (Matches.Player2ID = p2.ID)

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 
FROM  
Matches INNER JOIN 
Events ON Matches.EventID=Events.ID INNER JOIN 
Players one ON Matches.Player1ID = one.ID INNER JOIN
Players two ON Matches.Player1ID = two.ID

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