我有一个用于虚构健身应用程序的 MySQL 表。 假设该应用正在监控用户每天做俯卧撑的进度。
训练日
id | id_user | date | number_of_pushups
现在,我需要查找用户是否曾连续 5 天完成 100 次以上俯卧撑。
我知道这可能可以通过获取所有日期然后进行一些 php 循环来实现,但我想知道是否有可能在普通的 mysql 中做到这一点......
最佳答案
在MySQL中,最简单的方法是使用变量。以下获取具有 100 次或更多俯卧撑的所有日期序列:
select grp, count(*) as numdaysinarow
from (select (date - interval rn day) as grp, td.*
from (select td.*,
(@rn := if(@i = id_user, @rn + 1
if(@i := id_user, 1, 1)
) as rn
from trainingdays td cross join
(select @rn := 0, @i := NULL) vars
where number_of_pushups >= 100
order by id_user, date
) td
) td
group by grp;
这使用了这样的观察:当您从一系列递增的日期中减去一系列数字时,结果值是恒定的。
要确定是否连续有 5 天或更多天,请使用 max()
:
select max(numdaysinarow)
from (select grp, count(*) as numdaysinarow
from (select (date - interval rn day) as grp, td.*
from (select td.*,
(@rn := if(@i = id_user, @rn + 1
if(@i := id_user, 1, 1)
) as rn
from trainingdays td cross join
(select @rn := 0, @i := NULL) vars
where number_of_pushups >= 100
order by id_user, date
) td
) td
group by grp
) td;
然后,您的应用可以根据您喜欢的最小值检查该值。
注意:这假设每天只有一条记录。如果您要查找每天俯卧撑次数的总和,可以轻松修改上述内容。
关于mysql - 我需要找到任何 5 行匹配 where 子句并且它们出现 "in a row"(它们是邻居),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26306765/