2011-12-27 194 views
0

我有兩個表,遊戲和用戶設定了以下字段:MySQL查詢表連接

tblGAMES--> 
GAME_ID (int) primary key, 
P1_ID (int), 
P2_ID (int), 
P3_ID (int), 
P4_ID (int) 

tblUSERS--> 
USER_ID (int) primary key, 
FIRST_NAME (text), 
LAST_NAME (text) 

我正在查詢我的數據庫,打印出每場比賽行的細節。例如:但

GAME_ID:1, P1:1, P2:2, P3:3, P4:4 

不是打印出存儲在tblGAMES的ID我想打印出每個玩家的第一名稱出現的相應行中向tblUsers。這是可以使用單個查詢而不是多個查詢嗎?

end result-->GAME_ID:1, P1:David, P2:Paul, P3:John, P4:Bobby 

回答

1

你需要加入用戶表4倍......

select g.GAME_ID, 
     u1.FIRST_NAME as ulname, 
     u2.FIRST_NAME as u2name, 
     u3.FIRST_NAME as u3name, 
     u4.FIRST_NAME as u4name 
from tblGAMES as g 
    left join tblUSERS as u1 on g.P1_ID =u1.USER_ID 
    left join tblUSERS as u2 on g.P2_ID =u2.USER_ID 
    left join tblUSERS as u3 on g.P3_ID =u3.USER_ID 
    left join tblUSERS as u4 on g.P4_ID =u4.USER_ID 

(未經測試)

1

在你將要tblUSERS每一次引用JOIN查詢。事情是這樣的:

SELECT 
    tblGAMES.GAME_ID, 
    tblUSER1.FIRST_NAME AS P1, 
    tblUSER2.FIRST_NAME AS P2, 
    tblUSER3.FIRST_NAME AS P3, 
    tblUSER4.FIRST_NAME AS P4 
FROM tblGAMES 
    INNER JOIN tblUSERS AS tblUSER1 ON tblGAMES.P1_ID = tblUSER1.USER_ID 
    INNER JOIN tblUSERS AS tblUSER2 ON tblGAMES.P2_ID = tblUSER2.USER_ID 
    INNER JOIN tblUSERS AS tblUSER3 ON tblGAMES.P3_ID = tblUSER3.USER_ID 
    INNER JOIN tblUSERS AS tblUSER4 ON tblGAMES.P4_ID = tblUSER4.USER_ID 

請注意,我的語法可能需要一點調整,我沒有寫足夠的MySQL最近釋放,一方面它100%可靠。但你明白了。每個連接都被獨立地添加到整個產品中。

根據每個玩家的要求,您也可以更改JOIN類型。例如,如果某些遊戲是雙人遊戲,那麼您希望這些代碼是LEFT OUTER JOIN,以便更好地處理值爲null等。