简体   繁体   中英

MySQL - Get longest chain of rows with a certain value

I can simplify my table structure for the purposes of this question to the following:

http://sqlfiddle.com/#!2/dcdd3/1

I want to get the longest win streak for each user (ie the largest number of contiguous win=1 rows without a win=0 row in between, returned in the following format:

user_id | win_streak
--------------------
1       | 5
2       | 3
3       | 3

The current solution I have is to get all of the rows and build the results in a PHP foreach loop, but I can't help thinking that there is a way to do this in MySQL.

You need a column that defines the order of the wins. I was assuming this to be the auto_increment column id :

select
user_id, max(wins) as longest_winning_streak
from (
SELECT 
ugr.*
, @winstreak := if(@prev_user = user_id, if(won = 1, @winstreak + 1, 0), 1) as wins
, @prev_user := user_id
FROM `user_game_results` ugr
, (SELECT @winstreak := 0, @prev_user := null) var_init
ORDER BY user_id, id
) sq
group by user_id

Your desired result is not quite correct, user_id has 3 wins in a row.

看一下以前的答案:

http://stackoverflow.com/questions/15484908/mysql-count-the-number-of-consecutive-times-a-value-appears

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM