What's wrong with this simple MySQL syntax? Summing the dates - mysql

Among the rest, I've got three columns in my table:
start- timestamp, the default value is CURRENT_TIMESTAMP
duration- datetime, usually 0000-00-07 00:00:00 (one week)
end - timestamp, the default value is 0000-00-00 00:00:00
Here's what I do:
UPDATE `banners` SET `end` = `start` + `duration` WHERE `id` = 93
No errors appear, the id is exact - but the operation doesn't execute, the end field just remains at zeros.
What's wrong? Any quotes, brackets needed? I also tried making the middle field the timestamp type as well with no result.

Very possible, just a little ugly in terms of code...
UPDATE `banners`
SET `end` = FROM_UNIXTIME(UNIX_TIMESTAMP(`start`) + (UNIX_TIMESTAMP(`duration`) - UNIX_TIMESTAMP('1970-01-01 00:00:00')),'%Y-%d-%m %h:%i')
WHERE `id` = 93
...you just need to convert everything to seconds, add the duration from teh second one and then convert back to a datetime string for setting :)

You cannot add DATETIME values the same way you add numbers. What's the meaning of April 25, 2016 added to January 5, 2016?
You should store your durations using the smallest time unit that can be used to represent them as integer numbers and use the MySQL DATE_ADD() function instead of the addition.
For example, if duration is 1 WEEK then you can use any of:
UPDATE `banners` SET `end` = DATE_ADD(`start`, INTERVAL 1 WEEK) WHERE `id` = 93
UPDATE `banners` SET `end` = DATE_ADD(`start`, INTERVAL 7 DAY) WHERE `id` = 93
UPDATE `banners` SET `end` = DATE_ADD(`start`, INTERVAL 168 HOUR) WHERE `id` = 93

If duration is usually 1 week, you can use DATE_ADD() function of MySql
DATE_ADD(start,INTERVAL 7 DAY)
Hope that helps

Related

Looking for MySQL Default yesterday date

I am using MySql via terminal. Below is the command I have used to create table but it is showing date in YYYY-MM-DD HH:MM:SS (example: 2018-05-25 14:12:47)
create table test (foo int, ts timestamp default CURRENT_TIMESTAMP);
But I want by default it take yesterday date every time I insert data in (YYYY-MM-DD) format.
Please help me to find the command.
Thanks,
Amit
According to the official MySQL documentation https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add, you can do like this:
If you want to store the "yesterday" on creation:
ts TIMESTAMP NOT NULL DEFAULT NOW() - INTERVAL 1 DAY
If you want to store the "yesterday" on every update:
ts TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW() - INTERVAL 1 DAY
According to this answer Select records from NOW() -1 Day:
NOW() returns a DATETIME.
And INTERVAL works as named, e.g. INTERVAL 1 DAY = 24 hours.
So if your script is cron'd to run at 03:00, it will miss the first
three hours of records from the 'oldest' day.
To get the whole day use CURDATE() - INTERVAL 1 DAY. This will get
back to the beginning of the previous day regardless of when the
script is run.
Hope it helps!
DEFAULT values in MySQL must be constants. They can't be functions or expressions (with the exception of CURRENT_TIMESTAMP).
Source: http://dev.mysql.com/doc/refman/5.6/en/data-type-defaults.html
In addition you can add a trigger to your table for your requirement
Simply Create a Table without constraint
create table test (foo int, ts timestamp );
Then add a trigger to this table
CREATE TRIGGER settime
BEFORE INSERT on test
FOR EACH ROW BEGIN
IF new.`ts ` is null THEN
SET new.`ts ` = DATE_ADD(NOW(), INTERVAL -1 DAY);
END IF;
END;

UPDATE column where timediff is greater than 5 minutes

I have a table (sessions) which has 2 columns that I have to use for this query.
Session_Active (which is a tinyInt) and Last_active(which is a datetime).
I want to create a query that calculates the time difference between now and 'Last_active' for all tables WHERE 'Session_Active' is true, and if its greater than 5 minutes it should change 'Session_Active'.
This is the part that I have which works:
SELECT timediff(now(), `Last_Active`) from sessions WHERE `Session_Active` = true;
I have no clue at all how I can check if the difference is greater than 5 minutes, neither do I know where/how to put the UPDATE Session_Active = false (If the difference is 5 minutes or more)
Thanks in advance! (:
You can use the following solution using DATE_SUB:
UPDATE sessions SET `Session_Active` = 0
WHERE `Last_Active` <= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
AND `Session_Active` = 1
You want to use a timestamp solution?
You can use TIMESTAMPDIFF:
UPDATE sessions SET `Session_Active` = 0
WHERE TIMESTAMPDIFF(MINUTE, `Last_Active`, NOW()) >= 5
AND `Session_Active` = 1
Note: You should be careful with using TIMESTAMP! Some information why you shouldn't use TIMESTAMP: https://stackoverflow.com/a/35469149/3840840. On this answer there is a reference to this article describing the performance of DATETIME, TIMESTAMP and INT.
The TIMESTAMP solution is only working until 2038. This will be caused by the Year 2038 problem.
A very good explanation of this problem and what is happening in 2038: https://stackoverflow.com/a/2012620/3840840
You can use UNIX_TIMESTAMP(date)
When UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. The date argument may be a DATE, DATETIME, or TIMESTAMP string, or a number in YYMMDD, YYMMDDHHMMSS, YYYYMMDD, or YYYYMMDDHHMMSS format. The server interprets date as a value in the current time zone and converts it to an internal value in UTC. This is faster then DATE_SUB on large table set.
UPDATE sessions
SET `Session_Active` = 0
WHERE UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(`Last_Active`) > 300
AND `Session_Active` = 1

Get records between Two Dates with overlapping time intervals

I have the following database
CREATE TABLE `table` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`time` bigint(20) DEFAULT NULL,
`name` varchar(20) DEFAULT NULL,
`messages` varchar(2000) NOT NULL,
PRIMARY KEY (`id`)
)
INSERT INTO `table` VALUES (1,1467311473,"Jim", "Jim wants a book"),
(2,1467226792,"Tyler", "Tyler wants a book"),
(3,1467336672,"Phil", "Phil wants a book");
I need to get the records between date 29 Jun 2016 and 1 July 2016 for time intervals 18:59:52 to 01:31:12.
I wrote a query but it doesn't return the desired output
SELECT l.*
FROM table l
WHERE ((time >=1467226792) AND (CAST(FROM_UNIXTIME(time/1000) as time) >= '18:59:52') AND (CAST(FROM_UNIXTIME(time/1000) as time) <= '01:31:12') AND (time <=1467336672))
Any suggestions??
As I understand it, you're simply interested in all periods greater than '2016-06-29 18:59:52' and less than '2016-07-01 01:31:12' where the time element is NOT between '01:31:12' and '18:59:52'
I think you can turn that logic into sql without further assistance
Ah, well, here's a fiddle - left out all the from_unixtime() stuff because it adds unnecessary complication to an understanding of the problem - but adapting this solution to your needs is literally just a case of preceding each instance of the column time with that function:
http://rextester.com/OOGWB23993
If i got it right
SELECT l.*
FROM `table` l
WHERE time >=1467226792
AND time <=1467336672
AND CAST(FROM_UNIXTIME(time/1000) as time) >= '18:59:52'
AND FROM_UNIXTIME(time/1000) <= DATE_ADD(DATE_ADD(DATE_ADD(CAST(FROM_UNIXTIME(time/1000) as date), INTERVAL 25 HOUR), INTERVAL 31 MINUTE), INTERVAL 12 SECOND)

How can I get the date difference of a timestamp

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 :|

MySQL add 12 hours to a time field

I need to add 12 hours to a MySQL TIME field (not DATETIME) and I'm having trouble.
UPDATE `events`
SET start_time = DATE_ADD(start_time, INTERVAL 12 HOUR)
WHERE `start_time` < '11:00:00'
returns with no errors but doesn't change anything, I think because start_time is a TIME field.
UPDATE `events`
SET start_time = start_time + '12:00:00'
WHERE `start_time` < '11:00:00'
adds 12 seconds.
Try using ADDTIME instead of DATE_ADD. You could do SET start_time = ADDTIME(start_time, '12:00:00')
UPDATE `events`
SET start_time = start_time + INTERVAL 12 HOUR
WHERE `start_time` < '11:00:00'
The MySQL functions that accept INTERVAL arguments are mostly unnecessary; you can just add and subtract intervals with + and -.
set start_time = ADDTIME(start_time,'12:00:00')
DATE_ADD works fine with timestamp etc, but not with TIME
update my_table SET modified_date = ADDTIME(scheduled_date, '03:15:00')
This will add 3 hours , 15 minutes in modified_date
if the developer does not want to update data and wants to add hours or minutes to time. It can be done following way:
The developer can use an AddTime() function to add hours to time column in MySQL.
It can be used like below way:
AddTime(COLUMN,’01:00:00′) to add an hour in MySQL time column
AddTime(COLUMN,’00:01:00′) to add a minute in MySQL time column
sql query example:
select id,name,AddTime(login_time,'01:00:00') as login_time FROM `table`
First answer:
SET start_time = ADDTIME(start_time, '12:00:00')
Will only work if start_time is less than 12 hours.
If start_time is for example 13:00:00, then the end result will be 25:00:00, to get 01:00:00, you can use the following trick:
SET start_time = DATE_FORMAT(ADDTIME(CONCAT('1970-01-01 ', start_time), '12:00:00'), '%H:%i:%s')
(I used this to correct for the timezone)