Mysql gets the specified time range data

MySQL gets the data TO_DAYS(date) function within a certain time range.

to_days(): Returns the total number of days from 0000 to the current date.

Table of contents

1. Today (TO_DAYS())

2. Today yesterday (TO_DAYS())

3. Last 7 days (DATE_SUB())

5. This month (DATE_FORMAT())

6. Last month (PERIOD_DIFF()) 

7. This quarter

8. Last quarter

9. This year

​10. Last year

11. This week

12. last week

13. This month

​14. 6 months ago


Table data:


 1. Today (TO_DAYS())

select * from 表名 where to_days(字段名) = to_days(now());

2. Today yesterday (TO_DAYS())

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

 

3. Last 7 days (DATE_SUB())

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

 

5. This month (DATE_FORMAT())

SELECT * FROM 表名 WHERE DATE_FORMAT(字段名, ‘%Y%m') = DATE_FORMAT( CURDATE( ) , ‘%Y%m' )

6. Last month (PERIOD_DIFF()) 

SELECT * FROM 表名 WHERE PERIOD_DIFF( date_format( now( ) , ‘%Y%m' ) , date_format(字段名, ‘%Y%m') ) =1

7. This quarter

select * from `表名` where QUARTER(字段名)=QUARTER(now());

8. Last quarter

select * from `表名` where QUARTER(字段名)=QUARTER(DATE_SUB(now(),interval 1 QUARTER));

 

 

9. This year

select * from `表名` where YEAR(字段名)=YEAR(NOW());

10. last year

select * from `表名` where year(字段名)=year(date_sub(now(),interval 1 year));

11. This week

SELECT * FROM 表名 WHERE YEARWEEK(date_format(字段名,'%Y-%m-%d')) = YEARWEEK(now());

12. last week

SELECT * FROM 表名 WHERE YEARWEEK(date_format(字段名,'%Y-%m-%d')) = YEARWEEK(now())-1;

 Empty because the default is Sunday as the first day.

According to yearweek(date,mode), the second parameter can set the day of the week of the first day.

13. This month

select * from 表名 where date_format(字段名,'%Y-%m')=date_format(now(),'%Y-%m')

 14. 6 months ago

select * from 表名 where 字段名 between date_sub(now(),interval 6 month) and now();

Guess you like

Origin blog.csdn.net/wangshiqi666/article/details/130566585