mysql查询表连接

时间:2011-12-27 17:41:28

标签: mysql join

我有两个表,GAMES和USERS设置了以下字段:

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

2 个答案:

答案 0 :(得分: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 :(得分: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类型。例如,如果某些游戏是2人游戏,那么您希望这些游戏为LEFT OUTER JOIN,以便更好地处理null值等。