I'm trying to JOIN two tables in MySQL
. Here is my table:
Games Table :
GameID Date/Time PlayerOneID PlayerTwoID
13 12/10/2013 10:53:29 PM 1 2
14 12/10/2013 10:57:29 PM 1 2
15 12/10/2013 10:58:29 PM 2 1
I have another table contain the ID of a player and that players name.
Players Table :
1 Dan
2 Jon
I'd like the resulting table to look like the following:
GameID Date/Time PlayerOneID PlayerTwoID
13 12/10/2013 10:53:29 PM Dan Jon
14 12/10/2013 10:57:29 PM Dan Jon
15 12/10/2013 10:58:29 PM Jon Dan
Here's what I am currently doing:
SELECT Games.GameID, Games.`Date/Time`, Players.Name, PlayerTwoID
FROM Games
INNER JOIN Players
ON PlayerOneID = Players.ID
This gets PlayerOnes name, but I can't find away to get PlayerTwos name as well. I have tried using two INNER JOINS, but this hasn't worked. I've read a lot of posts here on the stack, but I haven't come across any solution that works. I am new to MySQL, so a follow up explanation would be very helpful.
You were on the right track, you do need to join to the Players table twice, like so:
SELECT Games.GameID, Games.`Date/Time`, p1.Name, p2.Name
FROM Games
INNER JOIN Players p1
ON PlayerOneID = p1.ID
INNER JOIN Players p2
ON PlayerTwoID = p2.ID
What you probably missed was using an alias (p1,p2) to differentiate between the two copies of the Players table you are joining to.
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.