Explain the method of date comparison size in Mysql in detail

  • 2021-10-25 00:05:16
  • OfStack

If you have a table product with a field add_time whose data type is datetime, someone might write sql like this:

The code is as follows


select * from product where add_time = '2013-01-12'

For this statement, if you store the format YY-mm-dd, then OK, if you store the format: 2013-01-12 23:23:56 This format is a tragedy, this is the part where you can use the DATE () function to return the date, so this sql should be handled as follows:

The code is as follows


select * from product where Date(add_time) = '2013-01-12' 

One more. What if you want to inquire about the products added in January 2013?

The code is as follows


select * from product where date(add_time) between '2013-01-01' and '2013-01-31'

You can also write this:


select * from product where Year(add_time) = 2013 and Month(add_time) = 1 

Do you know the role of mysql date function in dealing with date comparison problems?

Its date_col value is within the last 30 days:

The code is as follows


mysql> SELECT something FROM table 
 WHERE TO_DAYS(NOW()) - TO_DAYS(date_col) <= 30;
DAYOFWEEK(date)

Returns the week index for the date date (1= Sunday, 2= Monday, … 7= Saturday). These index values correspond to the ODBC standard.

The code is as follows


mysql> select DAYOFWEEK('1998-02-03'); 
 -> 3 
WEEKDAY(date)

Returns the week index of date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

The code is as follows


mysql> select WEEKDAY('1997-10-04 22:23:00'); 
 -> 5 
 mysql> select WEEKDAY('1997-11-05'); 
 -> 2 
DAYOFMONTH(date)

Returns the mid-month date of date, in the range of 1 to 31.

The code is as follows


mysql> select DAYOFMONTH('1998-02-03'); 
 -> 3 
DAYOFYEAR(date) 

Returns the number of days of date in a year, in the range of 1 to 366.

The code is as follows


mysql> select DAYOFYEAR('1998-02-03'); 
 -> 34 
MONTH(date) 

Returns the month of date, ranging from 1 to 12.

The code is as follows


mysql> select MONTH('1998-02-03'); 
 -> 2 
DAYNAME(date)

Returns the name of the week of date.

The code is as follows


select * from product where Date(add_time) = '2013-01-12' 
0

Returns the month name of date.

The code is as follows


select * from product where Date(add_time) = '2013-01-12' 
1

Returns the quarter in the date1 year, ranging from 1 to 4.

The code is as follows


select * from product where Date(add_time) = '2013-01-12' 
2

If you want to have a more in-depth and systematic study of mysql, you can refer to the classic book MySQL King's Promotion Road.

Summarize


Related articles: