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:
- Retrieve data from the past 7 days.
SELECT * FROM table_name
WHERE date_column >= DATE_SUB(CURDATE(), INTERVAL 7 DAY);
- Retrieve data from the past month.
SELECT * FROM table_name
WHERE date_column >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH);
- 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.