試試這個。 編輯,因爲它經過考慮到損失的行
SELECT
d.player_id,
MAX(d.winStreak) AS maxWinStreak
FROM (
SELECT
@cUser := 0,
@winStreak := 0
) v, (
SELECT
player_id,
won,
timestamp,
@winStreak := IF(won=1,IF(@cUser=player_id,@winStreak+1,1),0) AS winStreak,
@cUser := player_id
FROM (
(
-- Get results where player == player_id
SELECT
player_id,
won,
timestamp
FROM matchTable
) UNION (
-- Get results where player == opponent_id (loss=1 is good)
SELECT
opponent_id,
loss,
timestamp
FROM matchtable
)
) m
ORDER BY
player_id ASC,
timestamp ASC
) d
GROUP BY d.player_id
這是通過選擇全贏/輸計數的連勝。子查詢然後按player_id進行分組,並按照循環計算的最大winStreak輸出爲每個玩家。
它似乎對我的測試數據集反正很好地工作:)
要做到這一點更有效地我會重組,即
matches (
matchID,
winningPlayerID,
timeStamp
)
players (
playerID
-- player name etc
)
matchesHasPlayers (
matchID,
playerID
)
這將導致
SELECT
matches.matchID,
matchesHasPlayers.playerID,
IF(matches.winningPlayerID=matchesHasPlayers.playerID,1,0) AS won
matches.timestamp
FROM matches
INNER JOIN matchesHasPlayers
ORDER BY matches.timestamp
內查詢
產生於
SELECT
d.player_id,
MAX(d.winStreak) AS maxWinStreak
FROM (
SELECT
@cUser := 0,
@winStreak := 0
) v, (
SELECT
matchesHasPlayers.playerID,
matches.timestamp,
@winStreak := IF(matches.winningPlayerID=matchesHasPlayers.playerID,IF(@cUser=matchesHasPlayers.playerID,@winStreak+1,1),0) AS winStreak,
@cUser := matchesHasPlayers.playerID
FROM matches
INNER JOIN matchesHasPlayers
ORDER BY
matchesHasPlayers.playerID ASC,
matches.timestamp ASC
) d
GROUP BY d.player_id
我不認爲這可以用只有MySQL的代碼完成。我會做一個計算數據的cron腳本。 – cleanunicorn 2012-04-19 08:59:45
什麼意思是「最大的連勝」? – 2012-04-19 09:02:57
你有兩個記錄每個遊戲或只有一個?換句話說,如果opponant_id沒有相應的記錄,他們是player_id那麼你要算opponant_id /損失作爲該ID的勝利,對嗎? – davidethell 2012-04-19 09:03:34