MySQL INTERVAL Mins
Asked Answered
S

3

14

I am trying to get the all records which are 2 hours or more old using this query:

$minutes = 60 * 2

SELECT COUNT(id) AS TOTAL, job_id 
  from tlb_stats 
 WHERE log_time >= DATE_SUB(CURRENT_DATE, INTERVAL $minutes MINUTE) 
GROUP BY job_id

It only selects the recent records and skips the old. When I change log_time <= ... it only selects old and skips which are the new one.

What am I doing wrong?

Squashy answered 3/8, 2010 at 23:39 Comment(3)
You are doing all right - that is what this query should do.Nephro
why it isn't selecting the old records?Squashy
@jason4: because you want the records with a time less or equal (<=) to the current time minus 2 minutes, (i.e. now: 22:06, 2 mins ago is 22:04, so you want a record with 22:03, which is less then 22:04).Multiplicity
Q
25

Try:

$minutes = 60 * 2

SELECT COUNT(`id`) AS `TOTAL`, `job_id` 
  FROM `tlb_stats` 
  WHERE `log_time` < DATE_SUB(NOW(), INTERVAL $minutes MINUTE) 
  GROUP BY `job_id`
  • use backticks to quote fields (words like "total" and "id" may someday mean something in MySQL)
  • use NOW() for CURRENT_DATE just means 2010-08-04, not including the time
  • use < to get entries older than that date.
Quisling answered 4/8, 2010 at 0:9 Comment(0)
P
1
SELECT * FROM `table_name` WHERE CURTIME() >= (`colname` + INTERVAL 120 MINUTE)

Here, colname is the column where you added timestamp at the time when the record was created.

Pas answered 7/3, 2015 at 10:20 Comment(1)
Recommend rearranging the expression to WHERE colname <= ... so that INDEX(... colname) can be used.Treponema
M
0

You can also do it in this way:

$minutes = 60 * 2

SELECT COUNT(`id`) AS `TOTAL`,
       `job_id` 
FROM `tlb_stats` 
WHERE `log_time` < NOW() - INTERVAL $minutes MINUTE
GROUP BY `job_id`
Micronutrient answered 24/4, 2019 at 22:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.