The query keeps the streak count in a variable and as soon as there's a gap it resets the count to a large negative. It then returns the largest streak.
Depending on how many votes a user can have you might need to change -99999
to a larger (negative) value.
select if(max(maxcount) < 0, 0, max(maxcount)) streak
from (
select
if(datediff(@prevDate, datecreated) = 1, @count := @count + 1, @count := -99999) maxcount,
@prevDate := datecreated
from votes v cross join
(select @prevDate := date(curdate() + INTERVAL 1 day), @count := 0) t1
where username = 'bob'
and datecreated <= curdate()
order by datecreated desc
) t1;
http://sqlfiddle.com/#!2/37129/6
Update
Another variation
select * from (
select datecreated,
@streak := @streak+1 streak,
datediff(curdate(),datecreated) diff
from votes
cross join (select @streak := -1) t1
where username = 'bob'
and datecreated <= curdate()
order by datecreated desc
) t1 where streak = diff
order by streak desc limit 1
http://sqlfiddle.com/#!2/c6dd5b/20
Note, fiddle will only return correct streaks if run at the date of this post :)
Update 2
The query below works with tables that allow multiple votes per day by the same user by selecting from a derived table where duplicate dates are removed.
select * from (
select date_created,
@streak := @streak+1 streak,
datediff(curdate(),date_created) diff
from (
select distinct date(date_created) date_created
from votes where username = 'pinkpopcold'
) t1
cross join (select @streak := -1) t2
order by date_created desc
)
t1 where streak = diff
order by streak desc limit 1
http://sqlfiddle.com/#!2/5fc6d/7
You may want to replace select *
with select streak + 1
depending on whether you want to include the 1st vote in the streak.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…