Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with INTERVAL and CURDATE in MySQL

I'm building a chart and I want to receive data for each month.

Here's my first request which is working:

SELECT s.GSP_nom AS nom, timestamp, AVG( v.vote +  v.prix  ) /2 AS avg FROM votes_serveur AS v INNER JOIN serveur AS s ON v.idServ = s.idServ WHERE s.valide =1 AND v.date > CURDATE() -30 GROUP BY s.GSP_nom ORDER BY avg DESC 

But, in my case I've to write 12 request to receive data for the 12 previous months, is there any trick to avoid writing:

//  example for the previous month  AND v.date > CURDATE() -60 AND v.date < CURDATE () -30 

I heard about INTERVAL, I went to the MySQL doc but i didn't manage to implement it.

Any example of using INTERVAL please?

like image 827
sf_tristanb Avatar asked May 08 '10 09:05

sf_tristanb


People also ask

What is interval in MySQL?

MySQL INTERVAL() function returns the index of the argument that is more than the first argument. Syntax: INTERVAL(N,N1,N2,N3,...) It returns 0 if 1st number is less than the 2nd number and 1 if 1st number is less than the 3rd number and so on or -1 if 1st number is NULL. All arguments are treated as an integer.

What is MySQL Curdate?

MySQL CURDATE() Function The CURDATE() function returns the current date. Note: The date is returned as "YYYY-MM-DD" (string) or as YYYYMMDD (numeric). Note: This function equals the CURRENT_DATE() function.

How do I insert date in YYYY-MM-DD format in MySQL?

Introduction to MySQL DATE data type This format is fixed and it is not possible to change it. For example, you may prefer to use mm-dd-yyyy format but you can't. Instead, you follow the standard date format and use the DATE_FORMAT function to format the date the way you want. MySQL uses 3 bytes to store a DATE value.

How can use date and time function in MySQL?

MySQL SYSDATE() returns the current date and time in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS. uuuuuu format depending on the context of the function. MySQL TIME_FORMAT() converts a time in a formatted string using the format specifiers. MySQL TIME_TO_SEC() converts a time value in to seconds.


2 Answers

You need DATE_ADD/DATE_SUB:

AND v.date > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH)) AND v.date < (DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) 

should work.

like image 181
Pekka Avatar answered Oct 01 '22 11:10

Pekka


As suggested by A Star, I always use something along the lines of:

DATE(NOW()) - INTERVAL 1 MONTH 

Similarly you can do:

NOW() + INTERVAL 5 MINUTE "2013-01-01 00:00:00" + INTERVAL 10 DAY 

and so on. Much easier than typing DATE_ADD or DATE_SUB all the time :)!

like image 43
seddy Avatar answered Oct 01 '22 12:10

seddy