我有一张表来表示日历的日子。 我想要一个(好)查询(Mysql),它返回一个日历的最近连续日数,其中check = 1.
例如:
table "day"
+---------+------------+------+-------------+
| id | date | check| calendar_id |
+---------+-------------------+-------------+
| 1 | 2011-06-30 | 1 | 1 |
| 2 | 2011-07-01 | 0 | 2 |
| 3 | 2011-07-02 | 1 | 1 |
| 4 | 2011-07-03 | 0 | 3 |
| 5 | 2011-07-10 | 1 | 1 |
| 6 | 2011-08-20 | 1 | 1 |
| 7 | 2011-08-25 | 1 | 5 |
| 8 | 2011-08-28 | 0 | 1 |
| 9 | 2011-08-29 | 1 | 1 |
| 10| 2011-08-30 | 1 | 1 |
| 11| 2011-08-31 | 1 | 1 |
+---------+-------------------+-------------+
对于日历nº1,查询必须返回
+--------------------+
| number of days|
+--------------------+
| 3 |
+--------------------+
(2011-08-29,2011-08-30,2011-08-31)
此查询有效,但我不知道是否是一个好的
SELECT t.*, IF((@prev - INTERVAL 1 DAY = t.d or @prev is NULL) and @c <> -1, @c := @c + 1, @c := -1) AS streak, @prev := t.d
FROM (
SELECT date AS d
FROM day
WHERE calendar_id = 1
AND check = 1
order by d desc
) AS t
INNER JOIN (
SELECT @prev := NULL, @c := 0
) AS vars
ORDER BY streak DESC limit 1