MySQL Inner Join Between Two Tables

落爺英雄遲暮 提交于 2019-12-11 12:19:05

问题


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.


回答1:


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.




回答2:


select GameID, p1.name playerOneName,p2.name playerTwoName from
games inner join players p1 on games.playerOneID=p1.id
inner join players p2 on games.playerTwoID=p2.id
order by GameID asc;



来源:https://stackoverflow.com/questions/20527582/mysql-inner-join-between-two-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!