Calculate the longest winning / losing streak for the user

I have already managed to get this to work, but you need help in improving the query and optimizing it for additional parameters.

The request will calculate the longest lane for winning and losing the game, and so far I have managed to get this to work, extracting the winnings and losing as a separate request. But I would like to take them both at once. How can I get this to work by building this query even further (this one will calculate the longest pay line):

SELECT MIN( c.ID ) - a.ID + 1 as Streak
    FROM games AS a
    LEFT JOIN games AS b ON a.ID = b.id + 1 AND b.P1Outcome= 'win'
    LEFT JOIN games AS c ON a.ID <= c.id AND c.P1Outcome= 'win'
    LEFT JOIN games AS d ON c.ID = d.id - 1 AND d.P1Outcome= 'win'
    WHERE
      a.UsrID = x
      AND a.P1Outcome= 'win'
      AND b.ID IS NULL
      AND c.ID IS NOT NULL
      AND d.ID IS NULL
    GROUP BY a.ID
    ORDER BY Streak

ID = primary key in each game

P1Outcome = The result of users in the game

UsrID = user id

First of all, can there be any improvements, and if possible, can he also get a losing streak at the same time? Thank you for your time.

+3

All Articles