获取最近的连续日期MySQL

时间:2015-06-15 21:43:30

标签: php mysql date

我有这个MySQL表:

| Date           | Room | State |
|2015-06-15      | 26   | 1     | 
|2015-06-16      | 26   | 1     | 
|2015-06-17      | 26   | 1     | 
|2015-06-18      | 26   | 1     | 
|2015-06-20      | 26   | 1     | 
|2015-06-21      | 26   | 0     | 
|2015-06-22      | 26   | 0     | 
|2015-06-23      | 26   | 1     | 
|2015-06-24      | 26   | 0     | 
|2015-06-30      | 26   | 1     | 
|2015-07-01      | 26   | 1     |

我想获得有用的最近的第一个日期(这意味着连续的一天,State = 1)预订期(例如,2天)。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

SELECT d.*
FROM   dates d
WHERE  EXISTS(SELECT `Date`
              FROM   dates
              WHERE  `Room` = d.`Room`
                     AND `Date` = Date_add(d.`Date`, INTERVAL 1 DAY)
                     AND `State` = 1)
       AND d.`State` = 1;

2天。

SET @days=3;

SELECT d.*
FROM   dates d
WHERE  (SELECT Count(`date`)
        FROM   dates
        WHERE  `Room` = d.`Room`
               AND `Date` <= Date_add(d.`Date`, INTERVAL @days - 1 DAY)
               AND `Date` >= d.`Date`
               AND `State` = 1) >= @days
       AND d.`State` = 1; 

表示动态天数值。 我使用的测试数据:

create table Dates(
`Date` DATE,
`Room` INT DEFAULT 26,
`State` BOOL DEFAULT 0);

INSERT INTO  Dates (`Date`,`State`) VALUES
('2015-01-01',1),
('2015-01-02',0),
('2015-01-03',1),
('2015-01-04',1),
('2015-01-05',0),
('2015-01-06',1),
('2015-01-07',1),
('2015-01-08',1),
('2015-01-09',0),
('2015-01-10',1),
('2015-01-11',1),
('2015-01-12',1),
('2015-01-13',1);

查询实际返回所有可能的日期。要只获得一个日期,请在语句末尾添加LIMIT 1。但也许它可以帮助我获得可能的后期开始日。 第二个查询返回testdata以下日期:

2015-01-06  26  1
2015-01-10  26  1
2015-01-11  26  1