- 获取当前的日期时间:now
select now(); #获取当前的日期时间 - 当前日期、时间:curdate、curtime
select curdate(); # 当前日期
select curtime(); # 当前时间 - 日期加减:date_add、date_sub
select date_add(now(),interval ‘2’ day);
select date_add(now(),interval ‘2’ hour);
select date_add(now(),interval ‘2’ minute);
select date_add(now(),interval ‘2’ second);
select date_add(now(),interval ‘2’ week);
select date_add(now(),interval ‘2’ month);
select date_add(now(),interval ‘2’ quarter);
select date_add(now(),interval ‘2’ year);
select date_add(now(),interval ‘2:10:40’ hour_second); #可以一次性从时分秒分别变化
select date_add(now(),interval ‘-2:10:40’ hour_second); #可以一次性从时分秒分别变化,负号表示减,过去的时刻
函数形式:DATE_ADD(date,INTERVAL expr unit) —— DATE_SUB(date,INTERVAL expr unit)
expr:表示时间间隔值
unit:单位
date_sub参数参考date_add即可。 - 日期差异函数:datediff
select datediff(‘2020-02-20’, ‘2020-01-30’) #前面的日期减去后面的日期,返回天数
select datediff(‘2020-02-20’, ‘2020-04-10’) #前面的日期减去后面的日期,返回天数
select datediff(‘2020-02-20 08:20:30’, ‘2020-04-10 10:54:43’) #参与运算的是日期 - timediff(该函数的结果有范围限制)与 timestampdiff
-
timediff
select timediff(‘12:23:10’,‘10:10:35’) diff_time; #时间差,时分秒,但是该函数的结果有范围限制,只从:从-838:59:59到838:59:59
select timediff(‘2020-02-02 12:00:00’,‘12:00:00’) as diff_time; #前后格式不一致时,为Nullselect timediff(‘2020-01-01 00:00:00’, ‘2020-04-01 00:00:00’) as diff_hour; #结果有误,因为超出限制,事实上,3个月的时间,值远比结果大,要得到正确的,可以用:timestampdiff
-
功能较多的方式:timestampdiff
select timestampdiff(hour, ‘2020-01-01 00:00:00’, ‘2020-04-01 00:00:00’) as diff_hour; #返回的是相差的小时
select timestampdiff(day, ‘2020-01-01 00:00:00’, ‘2020-02-01 00:00:00’) as diff_day; #返回的是相差的天数
select timestampdiff(month, ‘2020-01-01 00:00:00’, ‘2020-02-01 00:00:00’) as diff_month; #返回的是相差的月份
select timestampdiff(year, ‘2020-01-01 00:00:00’, ‘2020-02-01 00:00:00’) as diff_year; #返回的是相差的年份
select timestampdiff(second, ‘2020-01-01 01:10:10’, ‘2020-01-01 00:00:00’) as diff_second; #返回的是相差的秒数
select timestampdiff(minute, ‘2020-01-01 01:10:10’, ‘2020-01-01 00:00:00’) as diff_minute; #返回的是相差的分钟
-
test
* 查询近90天每周的新人数量
select week(t1.order_time) as order_week,count(t1.user_id)
from (select * from orders group by user_id having min(order_time)) t1 where date_sub(curdate(), interval 90 day) <= t1.order_time
group by order_week;