select floor((unix_timestamp(substr('201402',1,6),'yyyyMM')-unix_timestamp(substr('20141112',1,6),'yyyyMM'))/2629495);
解释:
格式:两个时间的格式自己随意指定
数字2629495解释。一年有365天4小时58分56秒。折算下秒数再除以12,得到2629495。
然后自己理解下这个数字就明白了。
可以用datediff函数。
创建表及插入数据:
create table test
(begindate datetime,
enddate datetime);
insert into test values ('2015-01-01','2015-07-13')
执行:
select datediff(day,begindate,enddate) from test;
结果:
直接两个时间的年份相减*12加上两个月份相减即可了,例如2020-05-01与2021-03-04,就是(2021-2020)*12+(3-5)=10。