mysql根據時間範圍查詢

2021-09-08 21:37:21 字數 2799 閱讀 6915

select * from bank_statistics where day_time between '2018-06-01' and '2018-06-10';  # 根據兩端範圍查詢

select * from bank_statistics where day_time = '2018-05-24';    # 查詢某一天的

select * from bank_statistics where date_format(day_time,'%y-%m') = '2018-06'  # 查詢某月的

今天

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 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));
查詢當前這週的資料

select name,submittime from enterprise where yearweek(date_format(submittime,'%y-%m-%d')) = yearweek(now());
查詢上週的資料

select name,submittime from enterprise where yearweek(date_format(submittime,'%y-%m-%d')) = yearweek(now())-1;
查詢上個月的資料

select name,submittime from enterprise where date_format(submittime,'%y-%m')=date_format(date_sub(curdate(), interval 1 month),'%y-%m')

select * from user where date_format(pudate,'%y%m') = date_format(curdate(),'%y%m') ;

select * from user where weekofyear(from_unixtime(pudate,'%y-%m-%d')) = weekofyear(now())

select * from user where month(from_unixtime(pudate,'%y-%m-%d')) = month(now())

select * from user where year(from_unixtime(pudate,'%y-%m-%d')) = year(now()) and month(from_unixtime(pudate,'%y-%m-%d')) = month(now())

select * from user where pudate between 上月最後一天 and 下月第一天

查詢當前月份的資料

select name,submittime from enterprise   where date_format(submittime,'%y-%m')=date_format(now(),'%y-%m')
查詢距離當前現在6個月的資料

select name,submittime from enterprise where submittime between date_sub(now(),interval 6 month) and now();

實際專案 根據時間範圍查詢優化

根據所傳條件在sql中新增時間範圍 and stationdatee detailreportpojo.getenddate 需要兩個時間欄位都要有索引才得以快速查詢,資料量大的情況下並不是好辦法,一方面是表結構大,但是建立索引最好不要超過一定數量,所以盡量不要將索引浪費在多餘的字段上面,可以使用以...

mysql查詢時間範圍

前端傳入的引數確是 yyyy mm dd 的 沒有帶時分秒。如果按照下面這兩種方式會查不全 select from test where create time between 2018 07 30 and 2018 07 31 select from test where create time ...

Mysql查詢時間範圍

sql 今天 select from 表名 where to days 時間欄位名 to days now 昨天 select from 表名 where to days now to days 時間欄位名 1 近7天 select from 表名 where date sub curdate in...