Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL INTERVAL Mins

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?

like image 862
Maximus Avatar asked Aug 03 '10 23:08

Maximus


People also ask

What is interval in MySQL?

MySQL interval is an operator, which is based on the binary search algorithm to search the items and returns the value from 0 to N. It is mainly used to calculate the date and time values. We can use the following syntax to create an interval value: INTERVAL expr unit.

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.

What is Date_add in MySQL?

The DATE_ADD() function adds a time/date interval to a date and then returns the date.

What is Unix_timestamp in MySQL?

UNIX_TIMESTAMP() : This function in MySQL helps to return a Unix timestamp. We can define a Unix timestamp as the number of seconds that have passed since '1970-01-01 00:00:00'UTC. Even if you pass the current date/time or another specified date/time, the function will return a Unix timestamp based on that.


2 Answers

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.
like image 190
mvds Avatar answered Oct 20 '22 05:10

mvds


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.

like image 22
DeathRs Avatar answered Oct 20 '22 04:10

DeathRs