1. 程式人生 > >mysql 給定起止日期獲取之間的連續日期

mysql 給定起止日期獲取之間的連續日期

建立一個數字輔助表

CREATE TABLE `nums` (
  `key` int(11) NOT NULL,
  PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='數字輔助表';

建立一個儲存過程為數字輔助表增加資料

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `create_nums`(cnt int unsigned)
BEGIN
declare s int unsigned default 1;
    truncate table nums;
    insert into
nums select s; while s*2<=cnt do begin insert into nums select `key`+s from nums; set s=s*2; end; end while; END$$ DELIMITER ;

執行儲存過程,增加1-50000進入數字輔助表

call create_nums(50000);
輸入起止日期
SELECT
    @num :[email protected] + 1 AS id,
    date_format(
        adddate(
            '2015-10-2'
, INTERVAL @num DAY ), '%Y-%m-%d' ) AS date FROM nums, (SELECT @num := - 1) t WHERE adddate( '2015-10-2', INTERVAL @num DAY ) < '2016-10-01' ORDER BY date;