mysql sets the default time value

  • 2020-05-07 20:34:41
  • OfStack

So in order to

create_time datetime default now() 

Setting default values is not possible.
The alternative is to use the TIMESTAMP type instead of the DATETIME type.
CURRENT_TIMESTAMP: when I update this record, this field of the record does not change.
CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP: when I update this record, this field in the record will change. That is, the time becomes the time of the update. (note that 1 UPDATE sets 1 column to the value it already has, this will not cause the TIMESTAMP column to be updated, because if you set 1 column to its current value, MySQL ignores the change for efficiency.) If there are more than one TIMESTAMP column, only the first is automatically updated.
The TIMESTAMP column type automatically marks the operation INSERT or UPDATE with the current date and time.
If there are more than one TIMESTAMP column, only the first is automatically updated.
Automatic update of the first TIMESTAMP column occurs under any of the following conditions:
Column values are not explicitly specified in one INSERT or LOAD DATA INFILE statement.
The column values are not explicitly specified in one UPDATE statement and the other column values are changed. (note that 1 UPDATE sets 1 column to the value it already has, this will not cause the TIMESTAMP column to be updated, because if you set 1 column to its current value, MySQL ignores the change for efficiency.)
You explicitly set TIMESTAMP to be listed as NULL.
Column TIMESTAMP in addition to the first column can also be set to the current date and time by setting the column to NULL, or NOW().
You can also use trigger for this in versions 5.0 and above.

create table test_time ( 
id int(11), 
create_time datetime 
); 
delimiter | 
create trigger default_datetime before insert on test_time 
for each row 
if new.create_time is null then 
set new.create_time = now(); 
end if;| 
delimiter ; 

Related articles: