select t.months from (
with RECURSIVE months(months,num) as (
SELECT DATE_FORMAT((CURDATE() - INTERVAL 1 MONTH), '%Y-%m') AS 'months' , 1 as num
union all
SELECT DATE_FORMAT((CURDATE() - INTERVAL num+1 MONTH), '%Y-%m') AS 'months', num+1 as num from months where num<12
)select months,num from months
) t
结果:
去年本月前一月往前推一年的时间
select t.months,t.num from (
with RECURSIVE months(months,num) as (
SELECT DATE_FORMAT(DATE_SUB(CURDATE() - INTERVAL 1 MONTH,INTERVAL 1 YEAR),'%Y%m') AS 'months' , 1 as num
union all
SELECT DATE_FORMAT(DATE_SUB(CURDATE() - INTERVAL 1 MONTH,INTERVAL 1 YEAR)- INTERVAL num MONTH,'%Y%m') AS 'months', num+1 as num from months where num<12
)select months,num from months
) t
DATE_SUB() 函数从日期减去指定的时间间隔。
语法:DATE_SUB(date,INTERVAL expr type)