1

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

 _______________________________
| 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

4 回答 4

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)
于 2009-12-18T18:50:06.377 回答
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
于 2009-12-18T18:54:37.003 回答
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')
于 2009-12-18T18:43:21.397 回答
0

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

如果没有,会是这样的:

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

工作?

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

于 2009-12-18T18:37:47.960 回答