Working with INTERVAL and CURDATE in MySQL to Retrieve Data for Specific Time Periods
When working with temporal data, MySQL offers several functions to manipulate dates and time intervals. In your case, you aim to extract data for specific months while avoiding multiple queries.
To achieve this, you can utilize the INTERVAL keyword in conjunction with CURDATE(), a function that returns the current date. By subtracting an INTERVAL from CURDATE(), you can create a range that represents a specific time frame.
For instance, suppose you want to retrieve data for the previous month. You can use the following query:
AND v.date > (DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) AND v.date < CURDATE()
This query will select data from the table 'votes_serveur' where the 'date' column falls within the previous month's range.
Similarly, you can adjust the INTERVAL value to retrieve data for any desired time period.
For example, to retrieve data for the previous 12 months, you can use the following query:
AND v.date > (DATE_SUB(CURDATE(), INTERVAL 12 MONTH)) AND v.date < CURDATE()
This query will return data for the entire previous year.
By using INTERVAL with CURDATE(), you can flexibly filter temporal data and create dynamic time ranges, simplifying your data retrieval tasks and eliminating the need for multiple queries.
The above is the detailed content of How can I retrieve data for specific time periods in MySQL using INTERVAL and CURDATE()?. For more information, please follow other related articles on the PHP Chinese website!