我在mysql表中有一个列,列出了游戏中的获胜者。 我正在尝试找到一个查询,它将为每个玩家返回最长的胜利。 或者用php解释查询的方法。
在这种情况下,它会 凯特4, Ed 1, 迈克2, 哈利1,
**Winner**
Kate
Kate
Ed
Harry
Ed
Harry
Mike
Mike
Ed
Harry
Kate
Kate
Kate
Kate
Ed
提前道歉,因为我对这一切都很陌生。
答案 0 :(得分:6)
SELECT winner, MAX(winningStreak) FROM (
SELECT
winner,
IF(winner=@prev, @rownum:=@rownum+1, @rownum:=1) AS winningStreak,
@prev:=winner
FROM
yourTable
, (SELECT @prev:=NULL, @rownum:=1) vars
/*ORDER BY whateverDeterminesTheOrderOfTheWinners*/
)sq
GROUP BY winner
ORDER BY winningStreak DESC
您需要另一列来确定获奖者的顺序,就像您列出的那样,并调整查询的已过时部分。除此之外,这个查询有效,但在PHP中实际上更容易完成。
直播here。
答案 1 :(得分:2)
使用变量会使查询更简单,但我想用SQL来解决它。这是我的问题:
SELECT winner, COALESCE(MAX(id2-min_id1), 0)+1
FROM (
SELECT MIN(w1.id) min_id1, w1.winner, w2.id id2
FROM
winners w1 LEFT JOIN winners w2
ON w1.id < w2.id
AND w1.winner = w2.winner
WHERE
NOT EXISTS (SELECT NULL FROM winners w3
WHERE w3.winner != w1.winner
AND w3.id > w1.id AND w3.id < w2.id)
GROUP BY
w2.id, w1.winner
) s
GROUP BY
winner
请参阅小提琴here。我正在使用ID,因为没有ID或时间戳,无法确定SQL查询返回的行的顺序。这假设ID没有间隙。
答案 2 :(得分:1)
好的,轮到我...这假设id是auto_incrementing,没有间隙......
SELECT winner
, MAX(streak) longest_streak
FROM
( SELECT a.*
, MIN( c.id ) - a.id + 1 streak
FROM results a
LEFT
JOIN results b
ON a.id = b.id + 1
AND b.winner = a.winner
LEFT
JOIN results c
ON a.id <= c.id
AND c.winner = a.winner
LEFT
JOIN results d
ON c.id = d.id - 1
AND d.winner = a.winner
WHERE b.id IS NULL
AND c.id IS NOT NULL
AND d.id IS NULL
GROUP
BY a.id
) x
GROUP
BY winner
ORDER
BY longest_streak DESC;