mysql获取指定时间段中所有日期或月份(不设存储过程,不加表)

mysql获取一个时间段中所有日期或者月份

最近需要用mysql获取一个时间段中的所有月份,网上查都是要设置存储过程或者加一个日期表的,不满足我的需求。找资料加上自己试验,如下代码分享给大家

正文

1:获取时间段所有月份

select DATE_FORMAT(date_add('2020-01-20 00:00:00', interval row MONTH),'%Y-%m') date from
 ( 
    SELECT @row := @row + 1 as row FROM 
    (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t,
    (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2, 
    (SELECT @row:=-1) r
 ) se
 where DATE_FORMAT(date_add('2020-01-20 00:00:00', interval row MONTH),'%Y-%m') <= DATE_FORMAT('2020-04-02 00:00:00','%Y-%m')

2:获取时间段所有日期

select date_add('2020-01-20 00:00:00', interval row DAY) date from
 ( 
    SELECT @row := @row + 1 as row FROM 
    (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t,
    (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2, 
    (SELECT @row:=-1) r
 ) se
 where date_add('2020-01-20 00:00:00', interval row DAY) <= '2020-03-02 00:00:00'

备注:

(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t

这段代码表示数据条数限制,写两次查询的日期最多显示100条,写三次查询日期最多显示1000次,以此类推,根据你自己的需求决定
↓↓↓↓↓↓
下面是设置最多显示条数10000写法
mysql获取指定时间段中所有日期或月份(不设存储过程,不加表)_第1张图片
希望能帮助到你,萌新在线求带!!!

你可能感兴趣的:(mysql,mysql,java,数据库,sql)