2012-08-31 28 views
3

我已經實現了某種在線遊戲。現在我想展示一個統計數字,你可以看到誰是你最擅長的敵人。查詢找到玩得最多的敵人

我將遊戲存儲在數據庫中。玩家存儲在PLAYER1和PLAYER2字段中。這取決於哪一個邀請另一個。開始遊戲並邀請另一個玩家的是PLAYER1。

ID | PLAYER1 | PLAYER2 | GAMESTATE 

現在我有一些條目。讓我們猜我是一號球員,我的朋友(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 

謝謝您的幫助!

回答

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) 
+0

其實我得到了我和每個敵人的比賽總和。有關預期結果的更多詳細信息,請參閱我編輯的問題。 –

+0

然後取出WHERE條件。我會編輯它。 :) – tbl

+0

如果你對玩家1有不同於玩家2的另一個結果,你會期望什麼?像這樣一行:在你的入口表中有'5,1,3,1'? – tbl

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 

要了解一般情況下,它更復雜 - 你到GroupWise的最大值等

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 
+0

這個查詢並實際上對我的工作!但是我希望爲所有用戶提供一個查詢,而不是每個用戶查詢一次:/您可能會看到我編輯的問題 –

+0

啊,現在這是一個不同的問題,通過您選擇的平臺變得更加如此,並且缺乏排名和常見表格表達。 – podiluska

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 
+0

這個查詢確實對我有效!但是我想爲所有用戶提供一個查詢,而不是每個用戶查詢一次:/您可能會看到我編輯的問題 –