Mysql 返回最近连续天数的查询
我有一张代表日历日期的表格。 我想要一个好的Mysql查询,返回一个日历中最近连续的天数,check=1 例如:Mysql 返回最近连续天数的查询,mysql,sql,query-performance,Mysql,Sql,Query Performance,我有一张代表日历日期的表格。 我想要一个好的Mysql查询,返回一个日历中最近连续的天数,check=1 例如: table "day" +---------+------------+------+-------------+ | id | date | check| calendar_id | +---------+-------------------+-------------+ | 1 | 2011-06-30 | 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 |
+---------+-------------------+-------------+
对于第1个日历,查询必须返回
+--------------------+
| number of days|
+--------------------+
| 3 |
+--------------------+
2011-08-292011-08-302011-08-31
这个查询有效,但我不知道是否是一个好的查询
在这个网站上,你有着最令人满意的查询。@Gabriel,你关心的概念被称为运行、间隙和孤岛-下面是@fancyPants的问题
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