2013-02-17 45 views
2

用戶表:MySQL的:獲取兩行作爲一個

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

遊戲表:

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

的DB是一個簡單的多人遊戲。我需要一個查詢來獲得用戶2,數據,和雙贏的數據爲用戶。這在MySQL中可能嗎?任何幫助將不勝感激。

回答

4

你必須JOINusers兩次這樣的:

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 
+0

感謝,don'really知道怎麼回事,但它的工作那謝謝啦! – 2013-02-17 12:24:31

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 = ... 
+0

好的,我應該更頻繁地刷新,這與馬哈茂德賈馬爾的 – 2013-02-17 11:48:03

+1

相同的答案,但我很感激它! – 2013-02-17 12:25:09

+0

謝謝,我通過大寫所有'AS'關鍵字來打磨它:-) – 2013-02-17 12:28:47