MySQL 擷取某月所有的日期點,mysql日期

來源:互聯網
上載者:User

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

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.