When querying a query or a menu, you often want to query for a specified time or time period, for example, to query for information within one day, to query for information within a week, to query within one months.
Define and use the Date_sub () function to subtract a specified time interval from a date.
1. Syntax
Date_sub (Date,interval expr type)
DateThe argument is a valid date expression.
ExprParameters are the interval of time that you want to add.
The type parameter can be the following value:
| 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 |
A simple example assumes that we have the following table:
| OrderId |
ProductName |
OrderDate |
| 1 |
' Computer ' |
2012-12-29 16:25:46.635 |
Now, we want to subtract 2 days from "OrderDate".
We use the following SELECT statement:
SELECT Orderid,date_sub (Orderdate,interval 2 day) as Orderpaydate from Orders
Results:
| OrderId |
orderpaydate |
| 1 |
2012-12-27 16:25:46.635 |
3. Complex examples:
Query 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 one months:
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);
We can use the unused type, for example, if we want to query the order within two weeks, and we can say so.
It's so simple.
date_sub function in MySQL