How can I get the date difference of a timestamp - mysql

I am trying to create a query that will limit insertion into a table based on the last time the poster sent data to the table.
For example if you posted data to the table then you are locked out of the system for another 10 hours. Here is what I came up with so far. But I get nowhere with the actual results on the data. Any help?
SELECT DATE( `date` )
FROM tablename
WHERE DATE( CURDATE( ) ) < CURDATE( ) - INTERVAL 1002
DAY
LIMIT 0 , 30

This will return a single post from the last 10 hours, if it exists:
SELECT *
FROM tablename
WHERE `date` >= NOW() - INTERVAL 10 HOUR
LIMIT 1
I'm assuming date is declared as DATETIME, since actual DATE does not contain the time part and hence is only day-accurate.
If date is an integer UNIX timestamp, use this:
SELECT *
FROM tablename
WHERE `date` >= UNIX_TIMESTAMP(NOW() - INTERVAL 10 HOUR)
LIMIT 1

There are a number of ways you could do this. Perhaps if you have a user settings table you could simply add a "last_insert" field, and store the timestamp as an integer value- that would be a super simple way to do it- you could check the current timestamp vs user_settings.last_insert and voila!
I suppose you could use datetime too. Whatever floats the boat.

First of all, you need a DATETIME column and not a DATE column. Assuming that tablename.date is a DATETIME column, then 10 hours before right now is CURRENT_TIMESTAMP - INTERVAL 10 HOUR.

First of all create a Time (TIMESTAMP DEFAULT CURRENT_TIMESTAMP) columnt in your table. It will be automatically set to current date on row insert
Then check:
SELECT COUNT(*) FROM Table WHERE Time > NOW() - INTERVAL 10 HOUR
If its 1 or more - block
You must compare the time last post was put with current time, not current time with current time :|

Related

Date Interval Bug

I have a table which has a column called created DATETIME, When adding entries It works fine, but when It gets to Date Interval, It keeps on duplicating new entries. I'm trying to get Today's and Yesterday's entries. Today's works fine, but for Yesterday's, It also puts on Today's contents in query results which Is not what I want.
SELECT * FROM tab WHERE created > DATE_SUB(NOW(), INTERVAL $num DAY) ORDER BY created DESC LIMIT 9;
$num Is 1 for Today's entries, and It's 2 for Yesterday's. So basically an entry which Is created today, Is getting duplicated on Yesterday's query results.
You are getting the results you requested from the database. Namely any record that is greater than today minus however many days you put in.
The reason you get 0 records when you try #KenWhite's suggested of changing your > to = is because your field is DATETIME, so subtracting exactly 24 hours from NOW() yields the same exact time yesterday and you probably don't have a record that was written precisely at this time yesterday. Right?
What you'll have to do is test for records between two dates to get you want. Instead of NOW(), switch to CURDATE(), this way you can be assured you'll get every record for the datetime range you are looking for.
SELECT *
FROM tab
WHERE
created BETWEEN DATE_SUB(CURDATE(), INTERVAL $num DAY) AND DATE_SUB(CURDATE(), INTERVAL $num - 1 DAY)
ORDER BY created DESC LIMIT 9;
You can check out a SQLFiddle of this here: http://sqlfiddle.com/#!2/19d9b/12
With datetime/timestamp values, similar to floats, always use ranges with closed beginnings and open endings. So use '>=' and '<'.
For example to use the data of a single day:
SELECT ... FROM tab
WHERE created >= CURDATE() - INTERVAL #num:=? DAY
AND created < CURDATE() - INTERVAL #num DAY + INTERVAL 1 DAY
ORDER BY created DESC
LIMIT 9
;
With MySQL, generally prefer the timestamp type over the datetime type, as datetime doesn't carry timezone information.
Alternatives:
created_at timestamp NULL DEFAULT NULL COMMENT 'set by application',
created_at timestamp NOT NULL DEFAULT '1970-01-01 23:00:00' COMMENT 'set by application',
dbms_row_created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'set by DBMS',

MySQL select entries from last hour based on epoch field

I need to return all the entries in a MySQL database from the last hour. The database has a column named time that has epoch values in.
This bit of psuedo code is what I want to be able to achieve but am not sure how to do this in MySQL. In another language I'd check to see that the epoch value of time in each row is no more than 3,600 different.
SELECT * FROM dailyltc WHERE `time` <= 1 hour
Not using functions to convert your stored epoch value enables MySQL the use of an index. Because of that I prefer the calculate the limits with UNIX_TIMESTAMP instead of converting the stored value to a DATETIME value.
SELECT
*
FROM
dailyltc
WHERE
`time` > UNIX_TIMESTAMP(NOW() - INTERVAL 1 HOUR);
Should newer values exist then you can simply add the upper bound:
SELECT
*
FROM
dailyltc
WHERE
`time` > UNIX_TIMESTAMP(NOW() - INTERVAL 1 HOUR)
AND
`time` <= UNIX_TIMESTAMP(NOW());

MySQL query: get data in specific interval

I have a MySQL Table with one datetime column. I want to prevent that the PHP-script gets to much data. So i'm searching for a solution that a MySql query only selects rows which have a distance of 1 minute or whatever. is there something simple or do i have to code a for-loop with a new mysql query every time.
Example
timestamp
2012-09-25 00:00:00-->
2012-09-25 00:00:50
2012-09-25 00:01:23
2012-09-25 00:01:30-->
2012-09-25 00:02:33
2012-09-25 00:02:40
2012-09-25 00:03:01-->i want those
thanks in advance
Try this :
SELECT create_time
FROM timeTable
WHERE create_time
IN (
SELECT min( create_time )
FROM timeTable
GROUP BY FROM_UNIXTIME( UNIX_TIMESTAMP( create_time ) - MOD( UNIX_TIMESTAMP( create_time ) , 60 ) );
How it works :
i) Groups the table by datetime rounded to the interval, 1 minute (60 seconds) here.
ii) Gets the top row from each group.
This can be a good sampling criteria for your data.
This query can be optimized alot on these points:
i) Put a where clause for a date = REQUIRED DATE, and then do other operations on hour+minutes instead of whole datetime.
ii) If your interval is 1 minute, then substring of the timestamp or date_format can be tried too to round it off to nearest minute.
eg.
SELECT create_time
FROM timeTable
WHERE create_time
IN (
SELECT min( create_time )
FROM timeTable
GROUP BY DATE_FORMAT( `create_time` , 'Y-M-D %H:%i' )
);
Try this
SET #time := '1000-01-01 00:00:00';
SET #interval := 60;
SELECT colDate
FROM table
WHERE TIMESTAMPDIFF( SECOND, #time, colDate ) >= #interval
AND #time := colDate
How it works.
#interval is the time difference desired between the current and previous colDate. The first parameter in TIMESTAMPDIFF determines the unit of time that the interval will use. ex: SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.
#time keeps track of the previous colDate, and it is compared with the current row. If the difference between the previous and current colDate is equal to or greater than the interval, it is included.
WHERE timestamp LIKE '%:30:00%' will get you every 30 seconds..
But this will only work if you have uniform entries..if your timestamps dont all end evenly.. you'll need to let us know.
EDIT
I think you may be looking for this:
How do you select every n-th row from mysql

getting mysql dates 3 days earlier when all dates in timestamp format

I have all dates stored as timestamps (int) in the database.
how can I get dates that are exactly 3 days earlier?
I tried
SELECT date from user WHERE DATE_ADD(DATE( FROM_UNIXTIME( `created` ) ), INTERVAL 3 DAY) = CURDATE()
is that the best/most efficient way to do it?
i think the database prefer to only do the date add 2 times to define the range, like:
SELECT date FROM user
WHERE UNIX_TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL -3 DAY)) <= `created`
AND `created` < UNIX_TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL -2 DAY));
Test putting DESCRIBE keyword before SELECT in both case, and the database respond with how its going to perform the query
SELECT date
FROM user
WHERE created = UNIX_TIMESTAMP(CURRENT_DATE - INTERVAL 3 DAY)
Note: no function used on the created column in where clause. This query should be able to use index.

MySQL - return only entries from the past X days

I'm working with a database that has date information stored as a Unix timestamp ( int(11) ) and what I want to do is only return entries from the past X days, the past 90 days for example.
What I've come up with is:
SELECT * FROM mytable WHERE category=1 AND
FROM_UNIXTIME( time ) > DATE_SUB(now(), INTERVAL 91 DAY)
Where 'time' is the int(11) in the db. This seems to be working fine, but just wondering what others think of this.
SELECT * FROM mytable WHERE category=1 AND
time > (UNIX_TIMESTAMP() - ((60*60*24)*90))
or simply
SELECT * FROM mytable WHERE category=1 AND
time > (UNIX_TIMESTAMP() - (86400*90))
this is just comparing a number (seconds in this case)
This query is bound to cause you headaches down the way as MySQL needs to do the conversion of dates for every row making use of indexes impossible. Unix timestamps are numbers, so instead of converting a timestamp to another date format, convert your lookup dates to unix timestamps.
What is the reason for storing the timestamp as an int ? I would use the mysql DATETIME data type because you can use the many Date Time functions mysql has.
If you do not have control over the data type of this field I would convert your date to the unix timestamp int before you do your query and compare it that way.
Just thinking aloud... wouldn't doing it the other way around cause less work for the DB?
time > UNIX_TIMESTAMP( DATE_SUB(NOW(), INTERVAL 91 DAY) )