Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql select dates in 30-day range

Tags:

date

mysql

This must be simple but I fiddled with it, and didn't get anything I wanted. I have the following code:

SELECT id,title,start_date 
  FROM events 
 WHERE start_date > DATE_SUB(NOW(), INTERVAL 1 MONTH) 
  AND city = '$cityName' 
ORDER BY start_date DESC

Now this selects events with dates in this month, but the definition of this month shown in query is different than what I need. I need it to show me events within 30 days and not only this month i.e. august. If I insert an event in august it shows the outcome. If I do insert september, it doesn't even though it is less than 30 days away.

like image 465
sys_debug Avatar asked Aug 23 '12 19:08

sys_debug


People also ask

How do I select a date range in MySQL?

If you need to select rows from a MySQL database' table in a date range, you need to use a command like this: SELECT * FROM table WHERE date_column >= '2014-01-01' AND date_column <= '2015-01-01';

How do I query a date in MySQL?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column. (In our example, we use a column of the timestamp data type.)

How do I create a date row in MySQL?

The default way to store a date in a MySQL database is by using DATE. The proper format of a DATE is: YYYY-MM-DD. If you try to enter a date in a format other than the Year-Month-Day format, it might work but it won't be storing the dates as you expect.


1 Answers

You should change 1 MONTH to 30 DAY:

WHERE start_date > NOW() - INTERVAL 30 DAY

To limit it to 30 days in either direction:

WHERE start_date > NOW() - INTERVAL 30 DAY
AND start_date < NOW() + INTERVAL 30 DAY
like image 83
Mark Byers Avatar answered Nov 03 '22 00:11

Mark Byers