如何在单独的列中存储两组日期之间的每个日期

时间:2016-05-05 05:12:20

标签: mysql date datetime

我有一张像这样的表A:

id  |    valid_from_date    |      valid_to_date     |
 1  |  2015-05-01 23:15:01  |   2015-05-02 10:20:23  | 
 2  |  2015-07-13 10:25:02  |   2015-07-14 18:20:45  | 

我希望能够获得valid_from_date和amp;之间的所有日期。每个id的valid_to_date,格式如下,我打算将其放入新表中:

id  |   date     |
 1  | 2015-05-01 |
 1  | 2015-05-02 |
 2  | 2015-07-13 |
 2  | 2015-07-14 |

实现这一目标的最佳方式是什么?

谢谢。

1 个答案:

答案 0 :(得分:1)

我不知道这是最好的方式......但是它给出了必需的输出....

将tableb创建为:

CREATE TABLE `tableb` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dates` date DEFAULT NULL,
`aid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

现在,  <击>

<击>
insert into tableb(aid,dates) select id,date(valid_from_date) as dates
from tablea union select
id,date(valid_to_date) as dates  from tablea order by id;

<击>

可能是存储过程是正确的选项:

CREATE PROCEDURE `test_procedure`()
BEGIN
DECLARE aid INT;
DECLARE avalid_from_date date;
DECLARE avalid_to_date date;
DECLARE tempdt date;
DECLARE done INT DEFAULT FALSE;
DECLARE getdates CURSOR FOR SELECT * from tablea;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN getdates;

read_loop: LOOP
 FETCH getdates INTO aid,avalid_from_date,avalid_to_date;

    IF done THEN
  LEAVE read_loop;  
END IF;

set tempdt=date(avalid_from_date);

WHILE (tempdt <= date(avalid_to_date)) do
  insert into tableb(dates,aid) values( tempdt,aid);
  set tempdt=tempdt+INTERVAL 1 DAY;
end while;


 END LOOP;
 CLOSE getdates;
 END

现在,只是call test_procedure; 所有输出行都将插入tableb。