How can MySQL search for data from the past few days/months/years?

To query data from the past few days/months/years, you can use MySQL’s DATE_SUB function and CURDATE function to filter the data. Here are some sample queries:

  1. Retrieve data from the past 7 days.
SELECT * FROM table_name 
WHERE date_column >= DATE_SUB(CURDATE(), INTERVAL 7 DAY);
  1. Retrieve data from the past month.
SELECT * FROM table_name 
WHERE date_column >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH);
  1. Retrieve data from the past year.
SELECT * FROM table_name 
WHERE date_column >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR);

In the above example, table_name refers to the name of the data table, and date_column is the column that stores dates. By combining CURDATE() with the DATE_SUB function, you can filter out the data from the most recent time period that meets the criteria.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds