php - 如何检查mysql日期列中的连续天数

标签 php mysql

有一个列出健康锻炼的 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/

相关文章:

php - mySQL 根据 PHP 中的另一列获取列

mysql - 获取不包含 X 成分的食谱

php - 解析 swf/fla(使用 php?)

javascript - 在不重新加载页面的情况下将点击链接的 ID 传递给 PHP 代码

c# - 日期和时间字段 asp.net c#

php - 将MySQL数据转换为句子大小写

php - 如何在 DESC MySQL 中选择数字 5-10

php - 搜索引擎优化谷歌没有注意到我的网站

php - 使用 RegEx 将抓取限制为 X 个字符 + 其他规范

php - 如何在原则 2 中添加约束 `on-update-cascade`