3

我已经意识到某种在线游戏。现在我想展示一个统计数据,您可以在其中看到谁是您对抗最多的敌人。

我已将游戏存储在数据库中。玩家存储在字段 PLAYER1 和 PLAYER2 中。这取决于,哪一个邀请另一个。开始游戏并邀请另一人的是PLAYER1。

ID | PLAYER1 | PLAYER2 | GAMESTATE

现在我有一些条目。假设我是玩家 1,我的朋友 (2) 邀请了我两次,我也邀请了他一次。条目如下所示:

1  | 2       | 1       | 1
2  | 2       | 1       | 1
3  | 1       | 2       | 1
4  | 3       | 4       | 1  <-- some other random game

现在,我想知道我玩得最多的球员。我实际上需要一个选择来计算最常玩的玩家,但在这两种情况下(PLAYER1 或 PLAYER2)。

单个查询的最佳解决方案是什么?我可以使用MySQL UNION还是 GROUP BY?如果是,我该怎么办?

编辑:预期结果实际上是这样的:

PLAYER | MOST_ENEMY | GAMES
1      | 2          | 3
2      | 1          | 3
3      | 4          | 1
4      | 3          | 1

感谢您的帮助!

4

3 回答 3

2

那是你要的吗?

SELECT * FROM (
    SELECT 
      PLAYER1,
      PLAYER2,
      COUNT(*) CNT
    FROM
      (
        SELECT PLAYER1, PLAYER2 FROM matches 
        UNION ALL
        SELECT PLAYER2 PLAYER1, PLAYER1 PLAYER2 FROM matches
      ) sub
    GROUP BY
      sub.PLAYER1,
      sub.PLAYER2
    ) sub2
GROUP BY
  sub2.PLAYER1
HAVING
  sub2.CNT = MAX(sub2.CNT)
于 2012-08-31T10:17:22.533 回答
0

你在哪里 玩家 1...

select 
    case player1 when 1 then player2 else player1 end as player, 
    count(*) as games
from yourtable
where 1 in (player1, player2)
group by case player1 when 1 then player2 else player1 end 
order by count(*) desc
limit 1

要找到一般情况,它更复杂 - 你进入分组最大值等

create temporary table games (id int, player int)
insert games (id,player)
    select ID, PLAYER1 as player
    from yourtable
    union
    select ID, PLAYER2
    from yourtable

create temporary table gamecount (player1 int, player2 int, gamecount int)
insert gamecount (player1,player2,gamecount)
    select c1.player, c2.player as player2, COUNT(*) as gamecount
        from games c1
        inner join games c2
           on c1.ID = c2.id
           and c1.player<>c2.player

    group by c1.player, c2.player

select * from gamecount topscore
where not exists
(select * from gamecount high 
where high.player1 = topscore.player1 
and high.gamecount>topscore.gamecount)
order by player1, gamecount desc


drop temporary table gamecount
drop temporary table games  
于 2012-08-31T10:10:24.987 回答
0
select (case when player1< player2 then player1 else player2 end) first_player, 
(case when player1 > player2 then player1 else player2 end) second_player, 
count(*) games
 from game
where (player1 = 1 or player2 = 1) 
group by first_player, second_player
order by games desc
limit 1
于 2012-08-31T10:17:35.647 回答