简体   繁体   中英

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

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

If duration is usually 1 week, you can use DATE_ADD() function of MySql

DATE_ADD(start,INTERVAL 7 DAY)

Hope that helps

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 duration s 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM