乐闻世界logo
搜索文章和话题

How to subtract 30 days from the current datetime in mysql?

1个答案

1

When you need to subtract 30 days from the current date and time in MySQL, you can use the DATE_SUB() function or directly use the INTERVAL expression. Here are two methods illustrated below:

Method 1: Using DATE_SUB() Function

The DATE_SUB() function subtracts a specified time interval from a given date. Its basic syntax is:

sql
DATE_SUB(date, INTERVAL expr type)
  • date is the starting date
  • expr is the amount to subtract
  • type is the time unit, such as DAY, MONTH, or YEAR.

For example, to subtract 30 days from the current date, use the following SQL query:

sql
SELECT DATE_SUB(NOW(), INTERVAL 30 DAY);

Method 2: Using INTERVAL Expression

You can directly apply the - INTERVAL expression to subtract a specific time from a date. For instance, subtracting 30 days is written as:

sql
SELECT NOW() - INTERVAL 30 DAY;

This method is straightforward and concise, making it convenient for simple date and time operations.

Example Application Scenario

Suppose you manage an online store and need to query orders from the past 30 days. Use the following SQL query:

sql
SELECT * FROM orders WHERE order_date >= NOW() - INTERVAL 30 DAY;

In this example, the second method is used to obtain the date 30 days ago from the current timestamp, filtering orders within the last 30 days.

2024年8月7日 09:57 回复

你的答案