Mysql:时间sql函数整理

 

1.根据时间格式化出年,月,日

SELECT NOW();  ##now()表示当前系统时间(YYYY-MM-DD HH:mm:ss)2020-05-31 21:51:01
SELECT DATE_FORMAT(now(),'%Y-%m-%d');  ##DATE_FORMAT(date,format)格式化date时间格式(YYYY-MM-DD)
SELECT DATE_FORMAT(now(),'%Y-%m');  ##DATE_FORMAT(date,format)格式化date时间格式(YYYY-MM)
SELECT DATE_FORMAT(now(),'%Y');  ##DATE_FORMAT(date,format)格式化date时间格式(YYYY)

2,求两列的时间差

select TIMESTAMPDIFF(SECOND, '2018-03-20 09:00:00', '2018-03-22 10:00:00'); ##返回相差分钟数
select TIMESTAMPDIFF(MINUTE, '2018-03-20 09:00:00', '2018-03-22 10:00:00'); ##返回相差分钟数
select TIMESTAMPDIFF(HOUR, '2018-03-20 09:00:00', '2018-03-22 10:00:00'); ##返回相差分钟数
select TIMESTAMPDIFF(DAY, '2018-03-20 09:00:00', '2018-03-28 10:00:00'); ##返回相差分钟数
select TIMESTAMPDIFF(MONTH, '2018-03-20 09:00:00', '2018-11-01 10:00:00'); ##返回相差分钟数
select TIMESTAMPDIFF(YEAR, '2018-03-20 09:00:00', '2020-03-22 10:00:00'); ##返回相差分钟数

TIMESTAMPDIFF  计算时间差函数
SECOND 秒 SECONDS 
MINUTE 分钟 MINUTES 
HOUR 时间 HOURS 
DAY 天 DAYS 
MONTH 月 MONTHS 
YEAR 年 YEARS

3.常用的时间区间,日,周,月,季度,年

今天   select * from 表名 where to_days(时间字段名) = to_days(now());

昨天    SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ) – TO_DAYS( 时间字段名) <= 1

7天     SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(时间字段名)

近30天   SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(时间字段名)

本月     SELECT * FROM 表名 WHERE DATE_FORMAT( 时间字段名, ‘%Y%m’ ) = DATE_FORMAT( CURDATE( ) , ‘%Y%m’ )

上一月     SELECT * FROM 表名 WHERE PERIOD_DIFF( date_format( now( ) , ‘%Y%m’ ) , date_format( 时间字段名, ‘%Y%m’ ) ) =1

查询本周记录
select * from ht_invoice_information where WEEKOFYEAR(create_date)=WEEKOFYEAR(NOW());
#查询上周记录
select * from ht_invoice_information where create_date>=date_add(now(),interval -(8 + weekday(now())) day)
and create_date<=date_add(now(),interval -(1 + weekday(now())) day);

#或者

select * from `ht_invoice_information` where WEEKOFYEAR(create_date)=WEEKOFYEAR(DATE_SUB(now(),INTERVAL 1 week));
#查询本月数据
select * from ht_invoice_information where MONTH(create_date)=MONTH(NOW()) and year(create_date)=year(now());
#查询上月数据
select * from ht_invoice_information where create_date<=last_day(date_add(now(),interval -1 MONTH))
and create_date>=DATE_FORMAT(concat(extract(year_month from date_add(now(),interval -1 MONTH)),’01′),’%Y-%m-%d’);

#或者

select * from `ht_invoice_information` where MONTH(create_date)=MONTH(DATE_SUB(NOW(),interval 1 month))
and year(create_date)=year(now());
#查询本季度数据
select * from `ht_invoice_information` where QUARTER(create_date)=QUARTER(now());
#查询上季度数据
select * from `ht_invoice_information` where QUARTER(create_date)=QUARTER(DATE_SUB(now(),interval 1 QUARTER));
#查询本年数据
select * from `ht_invoice_information` where YEAR(create_date)=YEAR(NOW());
#查询上年数据
select * from `ht_invoice_information` where year(create_date)=year(date_sub(now(),interval 1 year));

参考:https://blog.csdn.net/icefan02/article/details/84550148博客

你可能感兴趣的:(MySQL)