Article directory
1. Function introduction
The DATE_FORMAT()
function is used to display date/time data in different formats.
The CURDATE()
function returns the current date.
TO_DAYS(date)
Returns a number of days (number of days since year 0) for the given date.
The NOW()
function returns the current system date and time.
YEARWEEK(date), YEARWEEK(date,mode)
returns the year and day of the week. The mode parameter works exactly the same as using the mode parameter to WEEK(). The year in the result may be different from the date parameter for the first and last week of the year in the year.
PERIOD_DIFF(P1,P2)
returns the number of months between periods P1 and P2. P1 and P2 are in YYYYMM or YYYYMM format. Note that neither the period parameters P1 nor P2 have date values.
The DATE_SUB()
function subtracts a specified time interval from a date.
Two, SQL statement
- today
SELECT * FROM table name WHERE TO_DAYS(field name) = TO_DAYS(NOW())
- yesterday
SELECT * FROM table name WHERE TO_DAYS( NOW( ) ) - TO_DAYS( field name) <= 1
- this week
SELECT * FROM table name WHERE YEARWEEK(DATE_FORMAT(field name,'%Y-%m-%d')) = YEARWEEK(now())
- last week
SELECT * FROM table name WHERE YEARWEEK(DATE_FORMAT(field name,'%Y-%m-%d')) = YEARWEEK(now())-1
- this month
SELECT * FROM table name WHERE DATE_FORMAT( field name, '%Y%m' ) = DATE_FORMAT( CURDATE( ),'%Y%m' )
- last month
SELECT * SELECT table name WHERE PERIOD_DIFF(DATE_FORMAT(now(),'%Y%m'),DATE_FORMAT(field name,'%Y%m') =1
- this quarter
SELECT * SELECT table name WHERE QUARTER(field name)=QUARTER(NOW());
- last quarter
SELECT * SELECT table name WHERE QUARTER(field name)=QUARTER(DATE_SUB(NOW(),interval 1 QUARTER));
- this year
SELECT * FROM table name WHERE YEAR (field name) = YEAR (NOW ());
- last year
SELECT * FROM table name WHERE YEAR (field name) = YEAR (DATE_SUB (NOW (), INTERVAL 1 YEAR));
Summarize
Work essay, I hope it can help everyone!
reference link
Function reference: https://www.w3cschool.cn/mysql/