查询找到最常玩的敌人

时间:2012-08-31 09:59:50

标签: mysql sql

我已经意识到某种在线游戏。现在我想显示一个统计数据,你可以看到谁是你最反对的敌人。

我已将游戏存储在数据库中。玩家存储在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

感谢您的帮助!

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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  

答案 2 :(得分: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