1

我在 mysql 表中有一个列,其中列出了游戏的获胜者。我正在尝试找到一个查询,该查询将为每个玩家返回最长的获胜次数。或者一种用 php.ini 解释查询的方法。

在这种情况下,它将是 Kate 4,Ed 1,Mike 2,Harry 1,

**Winner**
Kate
Kate
Ed
Harry
Ed
Harry
Mike
Mike
Ed
Harry
Kate    
Kate  
Kate
Kate
Ed

提前道歉,因为我对这一切都很陌生。

4

3 回答 3

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 中确实更容易完成。

看到它住在这里

于 2013-04-04T15:36:21.777 回答
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

在此处查看小提琴。我使用 ID 是因为没有 ID 或时间戳,无法确定 SQL 查询返回的行的顺序。这假设 ID 没有间隙。

于 2013-04-04T15:43:12.967 回答
1

好的,轮到我了……这假设 id 是自动递增的,没有间隙……

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;
于 2013-04-04T15:47:49.007 回答