MySQL datetime default time with interval
Is it possible to add to a default time with NOW(), 10 minutes?
I've tried something like that:
CREATE TABLE `table1` (
`date` DATETIME NOT NULL DEF开发者_运维百科AULT DATE_ADD(NOW(), INTERVAL 10 MINUTE)
);
However, it doesn't work.
I dont think you can do this.
The MySQL Documentation states that:
The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column
You could however use an insert-trigger to accomplish this. Set the default for the 'date' column to null, and use
CREATE TRIGGER settime
BEFORE INSERT on table1
FOR EACH ROW BEGIN
IF new.`date` is null THEN
SET new.`date` = DATE_ADD(NOW(), INTERVAL 10 MINUTE);
END IF;
END;
As of MySQL 8.0.13, you can now achieve this by wrapping the default expression in parentheses:
CREATE TABLE IF NOT EXISTS `datetime_interval_example`
(
...
`later` DATETIME NOT NULL DEFAULT (CURRENT_TIMESTAMP + INTERVAL 10 MINUTE),
...
);
The link posted by @DavidSteele in their answer demonstrates this as well.
精彩评论