我有一个结构如下的 MySQL 表:
饮料日志(ID,用户 ID,饮料 ID,时间戳)
我正在尝试计算用户(ID 为 1)每天至少记录 5 次饮料(ID 为 1)的连续天数的最大值。我很确定这可以使用如下视图来完成:
CREATE or REPLACE VIEW daycounts AS
SELECT count(*) AS n, DATE(timestamp) AS d FROM beverages_log
WHERE users_id = '1' AND beverages_id = 1 GROUP BY d;
CREATE or REPLACE VIEW t AS SELECT * FROM daycounts WHERE n >= 5;
SELECT MAX(streak) AS current FROM ( SELECT DATEDIFF(MIN(c.d), a.d)+1 AS streak
FROM t AS a LEFT JOIN t AS b ON a.d = ADDDATE(b.d,1)
LEFT JOIN t AS c ON a.d <= c.d
LEFT JOIN t AS d ON c.d = ADDDATE(d.d,-1)
WHERE b.d IS NULL AND c.d IS NOT NULL AND d.d IS NULL GROUP BY a.d) allstreaks;
但是,每次运行此检查时重复为不同用户创建视图似乎效率很低。MySQL 中有没有一种方法可以在单个查询中执行此计算,而无需创建视图或多次重复调用相同的子查询?