确定游戏的赢家并加入名称表

时间:2016-07-27 21:49:37

标签: mysql

我有两张桌子,一张名为玩家,一张名为匹配

播放器表包含2列:id,name

匹配表包含5列:player1,player2,goalsforplayer1,goalsforplayer2,matchid

寻找正确的查询以获取姓名(不是玩家ID)和匹配结果,最好比较目标玩家1和目标玩家2,以获得每场比赛的胜利者或平局。基本上是列出结果。

使用mysql查询是否可以这样?

2 个答案:

答案 0 :(得分:0)

这应该是您正在寻找的(获取球员名单及其总比赛结果),并应指导您正确的方向:

SELECT p.*, 
    (COUNT(CASE WHEN m1.goalsforplayer1 > m1.goalsforplayer2 THEN 1 ELSE NULL END) +
    (COUNT(CASE WHEN m2.goalsforplayer2 > m2.goalsforplayer1 THEN 1 ELSE NULL END)
    ) AS wins
FROM players p
INNER JOIN matches m1 ON p.id = m1.player1
INNER JOIN matches m2 ON p.id = m2.player2
GROUP BY p.id

加入matches表,按ID分组。使用聚合函数(此处为COUNT)来获取玩家赢得的匹配总数。如果您想要绘制,只需修改查询。

如果您正在寻找简单的结果(每方都有玩家),请使用:

SELECT p1.name AS player1, p2.name AS player2, m.goalsforplayer1, m.goalsforplayer2, m.matchid
FROM matches m
INNER JOIN players p1 ON p1.id = m.player1
INNER JOIN players p2 ON p2.id = m.player2

答案 1 :(得分:0)

你应该在玩家身上使用两个内部联接

select 
   b.name as nameplayer1
 , c.name as nameplayer2
 , a.goalsforplayer1
 , a.goalsforplayer2
 , a.matchid
from matches  as a 
inner join players as b on a.player1 = b.id
inner join players as c on a.player2 = c.id