Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display rows from MySQL where a datetime is within the next hour

Tags:

datetime

mysql

I always have trouble with complicated SQL queries.

This is what I have

$query = '
            SELECT id,
                   name, 
                   info, 
                   date_time
            FROM acms_events
                WHERE date_time = DATE_SUB(NOW(), INTERVAL 1 HOUR)
                    AND active = 1
            ORDER BY date_time ASC
            LIMIT 6
        ';

I want to get up to 6 rows that are upcoming within the hour. Is my query wrong? It does not seem to get events that are upcoming within the next hour when I test it.

What is the correct syntax for this?

like image 976
alex Avatar asked Apr 15 '10 05:04

alex


People also ask

How do I find the next record in MySQL?

You can use UNION to get the previous and next record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.

How do I search a date range in MySQL?

How to Select rows from a range of dates with MySQL query command. 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 can I get data between two dates and time in MySQL?

select *from yourTableName where yourColumnName between 'yourStartingDate' and curdate().

How do I query a timestamp in SQL?

To get a day of week from a timestamp, use the DAYOFWEEK() function: -- returns 1-7 (integer), where 1 is Sunday and 7 is Saturday SELECT dayofweek('2018-12-12'); -- returns the string day name like Monday, Tuesday, etc SELECT dayname(now()); To convert a timestamp to a unix timestamp (integer seconds):


1 Answers

I'm going to postulate that you're looking at a group of records that contain a range of DATETIME values, so you probably want something more like this:

SELECT id,
       name, 
       info, 
       date_time
FROM acms_events
    WHERE date_time < DATE_ADD(NOW(), INTERVAL 1 HOUR)
        AND date_time >= NOW()
        AND active = 1
ORDER BY date_time ASC
LIMIT 6

Otherwise, your query is looking for records with a date_time of exactly "now + 1 hour". I'm assuming all your dates aren't specific to that particular second. ;)

To clarify a bit, DATE_ADD() and DATE_SUB() return exact timestamps, so your query above roughly translates to something like SELECT ... WHERE date_time = '2010-04-14 23:10:05' ORDER BY ..., which I don't think is what you want.

like image 149
zombat Avatar answered Sep 23 '22 16:09

zombat