When querying data or menus, it is often necessary to query the specified time or time period. For example, to query the information within one day, to query the information within a week, and to query within a month, the engineers of Nanchang Website Construction Company are here to show you Introduce the DATE_SUB function, and explain it with examples, hoping to help new colleagues.
Definition and Usage
The DATE_SUB() function subtracts the specified time interval from a date.1. Grammar
DATE_SUB(date,INTERVAL expr type)The date parameter is a valid date expression. The expr parameter is the time interval you wish to add.
The type parameter can have the following values:
Type value
MICROSECOND |
SECOND |
MINUTE |
HOUR |
DAY |
WEEK |
MONTH |
QUARTER |
YEAR |
SECOND_MICROSECOND |
MINUTE_MICROSECOND |
MINUTE_SECOND |
HOUR_MICROSECOND |
HOUR_SECOND |
HOUR_MINUTE |
DAY_MICROSECOND |
DAY_SECOND |
DAY_MINUTE |
DAY_HOUR |
YEAR_MONTH |
Simple example
Suppose we have the following table:OrderId ProductName OrderDate
1 | 'Computer' | 2012-12-29 16:25:46.635 |
We use the following SELECT statement:
SELECT OrderId,DATE_SUB(OrderDate,INTERVAL 2 DAY) AS OrderPayDate FROM OrdersResult:
OrderId OrderPayDate
1 | 2012-12-27 16:25:46.635 |
query one day:
select * from table where to_days(column_time) = to_days(now());
select * from table where date(column_time) = curdate(); query one week: select * from table where DATE_SUB(CURDATE (), INTERVAL 7 DAY) <= date(column_time); Query a month: select * from table where DATE_SUB(CURDATE(), INTERVAL 1 MONTH) <= date(column_time); Query a specified number of days select * from table where DATE_SUB( CURDATE(), INTERVAL 2 DAY) <= date(column_time); The technicians of Nanchang Construction Website Company suggested that we can use different types according to our needs. For example, if we want to query orders within two weeks, then we can Express like this.
SELECT * FROM Orders where DATE_SUB(CURDATE(),INTERVAL 2 WEEK) <= date(column_time)It's that simple