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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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.*,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日期列中的连续天数全部内容,希望文章能够帮你解决php – 如何检查mysql日期列中的连续天数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。