1. 程式人生 > >MySQL獲取某月所有的日期點

MySQL獲取某月所有的日期點

1、問題

如題目所說,通過MySQL獲取某年某月所有的天數。如獲取2014年2月的所有日期。

2、處理過程

2.1 建立一個數字輔助表

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

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

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

2.3 通過數字輔助表獲取2014年2月1日到2014年2月31日

select CONCAT('2014-02-',lpad(n.key,2,'0') ) day  from nums n where n.key < 32

2.3 在2.2中得到的資料中小於等於2014年2月最後一天的日期就是我們要的結果

select * from (
select CONCAT('2014-02-',lpad(n.key,2,'0') ) day  from nums n where n.key < 32
) d where d.day <= last_day(DATE_FORMAT('2014-02-01','%Y-%m-%d')) ;