MySql 计算连续签到天数
(如果中间间断连续签到,将会从1开始)
思路如下:
获取当前签到的最后时间(今天或昨天), 定义一个变量@i 对签到时间进行天数自减, 然后查询出当前记录签到时间是否与自减后的时间匹配. 如果匹配表示天数是连续时间.
SELECT
count( 1 )
FROM
(
SELECT
date_sub( a.ct, INTERVAL 1 DAY ) signDate,
( @i := DATE_ADD( @i, INTERVAL - 1 DAY ) ) today
FROM
( SELECT ct FROM user_reach WHERE user_id = 14864795 ORDER BY ct DESC ) a
INNER JOIN (
SELECT
@i := max( ct ) AS signMax
FROM
user_reach
WHERE
user_id = 14864795
AND ( TO_DAYS( ct ) = TO_DAYS( curdate()) OR TO_DAYS( ct ) = TO_DAYS( DATE_ADD( curdate(), INTERVAL - 1 DAY ) ) )
) b
WHERE
b.signMax IS NOT NULL
AND TO_DAYS(
DATE_ADD( @i, INTERVAL - 1 DAY )) = TO_DAYS( date_sub( a.ct, INTERVAL 1 DAY ) )
) c