Working with INTERVAL and CURDATE in MySQL

2019-01-08 16:20发布

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?

3条回答
仙女界的扛把子
2楼-- · 2019-01-08 17:05

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 :)!

查看更多
孤傲高冷的网名
3楼-- · 2019-01-08 17:11

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.

查看更多
做自己的国王
4楼-- · 2019-01-08 17:13

I usually use

DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)

Which is almost same as Pekka's but this way you can control your INTERVAL to be negative or positive...

查看更多
登录 后发表回答