代码之家  ›  专栏  ›  技术社区  ›  True Soft

查询以从表中选择间隔

  •  1
  • True Soft  · 技术社区  · 16 年前

     _______________________________
    | 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 回复  |  直到 16 年前
        1
  •  2
  •   Peter Lang    16 年前
    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
  •  2
  •   Dan Soap    16 年前

    尝试

    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)
    
        3
  •  0
  •   dusoft    16 年前

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

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

    工作

        4
  •  0
  •   Charles Bretana    16 年前

    尝试

       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')