有一个列出健康锻炼的 MySQL 表。
recordId (primary key, ,integer, auto incrementing)
workoutNumber (integer)
date (date, ex- "2014-07-29")
我需要知道用户最近连续锻炼了多少天。我们可以在 MySQL 查询中执行此操作吗?我使用 PHP 作为应用程序语言。
最佳答案
我可以给你一个“纯 SQL”解决方案,使用临时变量:
此查询将创建一个包含 1
的连续天列,如果天数不连续,则创建 0
列。
select a.*
, coalesce(date_diff(a.date, @prevDate), 0) = 1 as consecutiveDay -- '1' if the days are consecutive,
-- '0' otherwise
-- (The first row will be 0)
, @prevDate := a.date as this_date -- You need to store the date of the current record
-- to compare it with the next one
from
(select @prevDate := null) as init -- This is where you initialize the temp
-- variable that will track the previous date
, yourTable as a
-- WHERE -- (Put any where conditions here)
order by a.date;
现在您可以使用上述查询作为第二个查询的行源对这些进行求和:
select sum(consecutiveDays) as consecutiveDays
from
( select a.*
, coalesce(date_diff(a.date, @prevDate), 0) = 1 as consecutiveDay
, @prevDate := a.date as this_date
from (select @prevDate := null) as init
, yourTable as a
-- WHERE -- (add where conditions here)
order by a.date
) as b
希望对你有帮助
关于php - 如何检查mysql日期列中的连续天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25005621/