MySQL - 从一个表中选择多个行,其ID存储在另一个表中

时间:2014-10-08 14:55:02

标签: mysql sql join

我很困惑使用JOIN - 语句从我的MySQL数据库中选择我的数据。 表格如下:

Table "Users"
+----+-------+----------+
| ID | Name  | Password |
+----+-------+----------+
| 1  | Mike  | test     |
| 2  | Tony  | test1    |
| 3  | Frank | test2    |
+----+-------+----------+

Table "Games"
+----+-----------+-----------+---------+---------+
| ID | Player1ID | Player2ID | ScoreP1 | ScoreP2 |
+----+-----------+-----------+---------+---------+
| 1  |         1 |         2 |       5 |       2 |
| 2  |         3 |         1 |       2 |       1 |
+----+-----------+-----------+---------+---------+

我想SELECT * FROM GAMES WHERE Player1ID=1 or Player2ID=1加上用户名,而不只是他们的ID。 有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

使用不同的别名加入users表两次以区分它们

select g.*, u1.name as player1, u2.name as player2
from games g
join users u1 on u1.id = g.player1id
join users u2 on u2.id = g.player2id