MySQL:获取两行作为一个

时间:2013-02-17 11:38:37

标签: mysql sql

用户表:

id  |   win  |   lose
0   |   1    |   2
1   |   2    |   8

游戏桌:

id  |  user1  |  user2  |  data
0   |  0      |  1      |  'some text'

数据库用于简单的多人游戏。我需要一个查询来获取两个用户的user2,数据,和双赢数据。这在MySQL中是否可行?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

你必须JOIN两次users这样的表:

SELECT
  u1.win  AS win1,
  u1.lose AS lose1,
  u2.win  AS win2,
  u2.lose AS lose2,
  ...
FROM games g
INNER JOIN users u1 ON g.user1 = u1.id
INNER JOIN users u2 ON g.user2 = u2.id

答案 1 :(得分:1)

您可以加入users表两次:

SELECT
    games.user2 AS user2_id
    games.data AS games_data
    user1.win AS user1_win,
    user1.lose AS user1_lose,
    user2.win AS user2_win,
    user2.lose AS user2_lose
FROM games
JOIN users AS user1 ON user1.id = games.user1
JOIN users AS user2 ON user2.id = games.user2
WHERE games.id = ...