Home > Database > Mysql Tutorial > How to Retrieve MySQL Records from the Last 30 Days, Including Today?

How to Retrieve MySQL Records from the Last 30 Days, Including Today?

DDD
Release: 2024-12-05 17:17:14
Original
742 people have browsed it

How to Retrieve MySQL Records from the Last 30 Days, Including Today?

How to Select Database Records Between Today and Last 30 Days with MySQL

This question seeks to retrieve records added within the last 30 days, with a required date conversion for display. The provided query attempts to use DATE_FORMAT within the WHERE clause, but it doesn't restrict the selection as intended.

Solution

The correct solution involves applying DATE_FORMAT in the SELECT clause:

SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
Copy after login

Reason for Correction

MySQL's DATE_FORMAT function converts a date to a specific format, but it doesn't modify the underlying date value. Therefore, it should be applied after the WHERE clause, which specifies the date range of interest.

Additional Considerations

If create_date is stored as a DATETIME with a non-zero time component, using CURDATE() in the WHERE clause will not select today's records. To account for this, use NOW() instead:

SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
Copy after login

The above is the detailed content of How to Retrieve MySQL Records from the Last 30 Days, Including Today?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template