查询从表中选择间隔

时间:2009-12-18 18:28:19

标签: mysql select intervals

我有一个定义时间间隔的表。

 _______________________________
| id | description | start_date |
|____|_____________|____________|
|  1 | First       |    NULL    |
|  3 | Third       | 2009-12-18 |
|  5 | Second      | 2009-10-02 |
|  4 | Last        | 2009-12-31 |
|____|_____________|____________|

它只存储开始日期,结束日期是下一个日期之前的一天。

我想得到下一个结果:

 ____________________________________________
| id | description | start_date |  end_date  |
|____|_____________|____________|____________|
|  1 | First       |    NULL    | 2009-10-01 |
|  5 | Second      | 2009-10-02 | 2009-12-17 |
|  3 | Third       | 2009-12-18 | 2009-12-30 |
|  4 | Last        | 2009-12-31 |    NULL    |
|____|_____________|____________|____________|

我应该如何编写此查询,因为一行包含其他行的值?

(我认为MySQL函数DATE_SUB可能很有用。)

4 个答案:

答案 0 :(得分:2)

select id, description, start_date, end_date from
  (
    select @rownum_start:=@rownum_start+1 rank, id, description, start_date
    from inter, (select @rownum_start:=0) p
    order by start_date
  ) start_dates
left join
  (
    select @rownum_end:=@rownum_end+1 rank, start_date - interval 1 day as end_date
    from inter, (select @rownum_end:=0) p
    where start_date is not null
    order by start_date
  ) end_dates
using (rank)

其中inter是您的表格

这实际上会返回:

mysql> select id, description, start_date, end_date from ...
+----+-------------+------------+------------+
| id | description | start_date | end_date   |
+----+-------------+------------+------------+
|  1 | First       | NULL       | 2009-10-01 |
|  5 | Second      | 2009-10-02 | 2009-12-17 |
|  3 | Third       | 2009-12-18 | 2009-12-30 |
|  4 | Last        | 2009-12-31 | NULL       |
+----+-------------+------------+------------+
4 rows in set (0.00 sec)

答案 1 :(得分:2)

SELECT d.id, d.description, MIN(d.start_date), MIN(d2.start_date) - INTERVAL 1
DAY AS end_date
FROM start_dates d
LEFT OUTER JOIN start_dates d2 ON ( d2.start_date > d.start_date OR d.start_date IS NULL )
GROUP BY d.id, d.description
ORDER BY d.start_date ASC

答案 2 :(得分:0)

如果您使用的是PHP,只需在脚本中计算上一个日期。那更容易。

如果没有,会是这样的:

SELECT ID,description,start_date,start_date-1 AS end_date FROM ...

工作?

更新:部分工作,因为它返回20091224 for startdate 2009-12-25但不适用于2009-12-01等日期。

答案 3 :(得分:0)

   Select d.Id, d.Description, d.Start_Date, 
       n.Start_Date - 1 EndDate
   From Table d 
     Left Join Table n
        On n.Start_Date = 
              (Select Min(Start_date)
               From Table
               Where Start_Date > Coalesce(d.Start_Date, '1/1/1900')