同一张表上有针对不同用户的多个联接

时间:2019-05-25 23:10:42

标签: mysql database

我有一个纸牌游戏。每个房间有4名玩家。我的数据库(MySQL)中有2个表,如下所示:

表nr 1:“房间”

id: Int
playerid1: Int
playerid2: Int
playerid3: Int
playerid4: Int

表nr 2:“玩家”

id: Int
name: Varchar
picture: varchar

我想做的是返回查询中的所有房间并同时获取玩家照片。通过加入获得单个玩家的图片很容易,但是我如何同时为所有4个玩家做到呢?

结果应该是这样的:

id = 123
playerid1 = 1
playerid2 = 2
playerid3 = 3
playerid4 = 4
playerpic1 = "one.jpg"
playerpic2 = "two.jpg"
playerpic3 = "three.jpg"
playerpic4 = "four.jpg"

预先感谢

1 个答案:

答案 0 :(得分:0)

您需要将表roomsplayers的4个联接:

select r.id,
  p1.id, p1.picture,
  p2.id, p2.picture,
  p3.id, p3.picture,
  p4.id, p4.picture
from rooms r
inner join players p1 on p1.id = r.playerid1
inner join players p2 on p2.id = r.playerid2
inner join players p3 on p3.id = r.playerid3
inner join players p4 on p4.id = r.playerid4