gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:39:38 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com