时间:2021-07-01 10:21:17 帮助过:2人阅读
因为默认情况下充许为空,当插入值时,分两种情况:第一列与第二列情况 explicit_defaults_for_timestamp=false [默认值]
mysql> create table timestamp(id int not null auto_increment,time1 timestamp,time2 timestamp,primary key(id))engine=innodb; Query OK, 0 rows affected (0.27 sec) mysql> insert into timestamp(id) values(1); Query OK, 1 row affected (0.21 sec) mysql> select * from timestamp; +----+---------------------+---------------------+ | id | time1 | time2 | +----+---------------------+---------------------+ | 1 | 2016-07-02 17:12:28 | 0000-00-00 00:00:00 | +----+---------------------+---------------------+ 1 row in set (0.19 sec) mysql> mysql> show create table timestamp;
CREATE TABLE `timestamp` ( `id` int(11) NOT NULL AUTO_INCREMENT, `time1` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `time2` timestamp NOT NULL DEFAULT ‘0000-00-00 00:00:00‘, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
2列TIMESTAMP未声明为NULL的默认行为
timestamp有两个属性,分别是CURRENT_TIMESTAMP 和ON UPDATE CURRENT_TIMESTAMP两种,使用情况分别如下: 1. CURRENT_TIMESTAMP 当要向数据库执行insert操作时,如果有个timestamp字段属性设为 CURRENT_TIMESTAMP,则无论这个字段有没有set值都插入当前系统时间 2. ON UPDATE CURRENT_TIMESTAMP 当执行update操作时,并且字段有ON UPDATE CURRENT_TIMESTAMP属性。则字段无论值有没有变化,它的值也会跟着更新为当前UPDATE操作时的时间。
从MySQL5.6.6开始这种默认设置的方法被废弃了。在MySQL启动时会出现以下警告:
1 2 3 |
[Warning] TIMESTAMP with implicit DEFAULT value is deprecated.
Please use --explicit_defaults_for_timestamp server option
(seedocumentation for more details).
|
关闭警告,在my.cnf中加入
1 2 |
[mysqld]
explicit_defaults_for_timestamp= true
|
重启MySQL后错误消失,这时TIMESTAMP的行为如下:
mysql> create table timestamp1(id int not null auto_increment,time1 timestamp,time2 timestamp,primary key(id))engine=innodb; Query OK, 0 rows affected (0.11 sec) mysql> insert into timestamp1(id) values(1); Query OK, 1 row affected (0.18 sec) mysql> show create table timestamp1; CREATE TABLE `timestamp1` ( `id` int(11) NOT NULL AUTO_INCREMENT, `time1` timestamp NULL DEFAULT NULL, `time2` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 mysql> select * from timestamp1; +----+-------+-------+ | id | time1 | time2 | +----+-------+-------+ | 1 | NULL | NULL | +----+-------+-------+ 1 row in set (0.18 sec)
TIMESTAMP 不设置是否为NULL
TIMESTAMP 默认设置为NOT NULL
Note:
以上内容和存储引擎选择无关。
MySQL 5.6 中 TIMESTAMP 的变化
标签: