有一个列出健康训练的MySQL表。
recordId (primary key, ,integer, auto incrementing)
workoutNumber (integer)
date (date, ex- "2014-07-29")
我需要知道用户最近连续几天的工作时间。我们可以在MySQL查询中执行此操作吗?我使用PHP作为应用程序语言。
答案 0 :(得分:1)
我可以给你一个纯粹的SQL"解决方案,使用临时变量:
此查询将创建连续几天1
s的列,如果日期不连续则创建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
希望这有帮助
答案 1 :(得分:0)
你可以这样做。
将前一天与当天和昨天与前一天相结合。此连接看起来像这样:
SELECT *
FROM table AS t1 INNER JOIN table AS t2 ON t1.date = SUBDATE(t2.date, 1) --or whatever you need to get the previous day
您现在会注意到未配对的天数在边界上,而配对天数则在连续的间隔内。要获得边界,必须使用外连接。
SELECT *
FROM table AS t1 FULL OUTER JOIN table AS t2 ON t1.date = SUBDATE(t2.date, 1)
现在您需要的是选择那些未配对的日期:
SELECT *
FROM table AS t1 FULL OUTER JOIN table AS t2 ON t1.date = SUBDATE(t2.date, 1)
WHERE t1.date IS NULL OR t2.date IS NULL;
当t1.date IS NULL
为开始日时。当t2.date IS NULL
为结束日时。
只需获取所需内容的MAX()
:
SELECT MAX(t2.date)
FROM table AS t1 FULL OUTER JOIN table AS t2 ON t1.date = SUBDATE(t2.date, 1)
WHERE t1.date IS NULL;
免责声明我即时记下了这个答案,-1
,IS NULL
或MIN()
vs MAX()
可能是错的,但基本的想法应该清楚。
作为解释,你想要的是:
t1 t2
NULL 16/07/1994 <-- interesting join (start of an interval)
16/07/1994 17/07/1994
17/07/1994 18/07/1994
18/07/1994 NULL <-- interesting join (end of an interval)