MySQL query to date methods

If there is a sheet product has a field add_time, its data type is datetime, someone might write sql:

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

For this statement, if you store format is YY-mm-dd is the case, then OK, if you store the format: 2013-01-12 23:23:56 this format you on the tragedy, which is you can use dATE () function is used to return part of the date, so this should be a process sql:

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

If the date + time according to mode (2013-01-1223: 23: 56- time accurate to the second) query the database, the timestamp can be used () function to query:

select * from product where timestamp(add_time) = '2013-01-12 23:23:56';

Query or a time range, you can use:

select * from product where timestamp(add_time) between '2013-01-12 03:23:56' and '2013-01-12 23:23:56';

or

select * from product where timestamp(add_time) >= '2013-01-12 03:23:56' < '2013-01-12 23:23:56';

One more, if you want to query in January 2013 added products?


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

You can also write:

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

These you know your role in the process of comparing the date of issue of mysql date functions, right?

Date_col its value is within the last 30 days:

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

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

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

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

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

DAYOFYEAR (date)
Returns the number of days of date of the year, in the range of 1-366.

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

MONTH (date)
Returns the date of the month, the range of 1 to 12.

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

DAYNAME (date)
Returns the name of the date of the week.

| mysql> select DAYNAME("1998-02-05"); 
-> 'Thursday' |

MONTHNAME (date)
Returns the month name of date.

| mysql> select MONTHNAME("1998-02-05"); 
-> 'February' |

QUARTER (date)
Returns the quarter of the year in the date range of 1-4.

| mysql> select QUARTER('98-04-01'); 
-> 2 |
发布了45 篇原创文章 · 获赞 1 · 访问量 1100

Guess you like

Origin blog.csdn.net/lqq404270201/article/details/103315505