timestamp类型

表结构

 
  

create table t1(
id int primary key auto_increment,
dt datetime,
ts timestamp
);

 

show create table

Table: t1
Create Table: CREATE TABLE `t1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dt` datetime DEFAULT NULL,
  `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

 datetime类型,默认值为null,而timestamp类型,默认值是当前时间,"ON UPDATE CURRENT_TIMESTAMP"表示更新记录时,当前字段的值会刷新 

 

insert into t1 values ();

 执行结果 

+----+------+---------------------+
| id | dt   | ts                  |
+----+------+---------------------+
|  1 | NULL | 2018-06-26 16:22:51 |
+----+------+---------------------+

 

更新记录

update t1 set dt = 180626162707;
select * from t1;

执行结果

+----+---------------------+---------------------+
| id | dt                  | ts                  |
+----+---------------------+---------------------+
|  1 | 2018-06-26 16:27:07 | 2018-06-26 16:27:10 |
+----+---------------------+---------------------+ 

timestamp字段的值同步更新了。

 

TIMESTAMP变体:字段名 timestamp [默认值] [是否同步更新]

1.

ts timestamp

相当于

ts timestamp default currrent_timestamp on update current_timestamp

 创建记录时,使用当前时间,并且更新记录时同步更新该字段

2.

ts timestamp default current_timestamp

创建记录时使用当前时间,但是更新记录时,该字段值保持不变

3.

ts timestamp default "18-06-27 12:23:34"

创建记录时使用特定时间,但是更新记录时,该字段值保持不变

4.

ts timestamp on update current_timestamp

创建记录时,该字段值为"0",更新记录时才会将该字段值设置为当前时间

5.

ts timestamp default 'yyyy-mm-dd hh:mm:ss' on update current_timestamp

创建记录时,使用自定义的时间值,只有等到更新记录时,该字段值才会使用当前时间

 

 

create table t2( 
    id int primary key auto_increment,
    name varchar(20), 
    t1 timestamp, 
    t2 timestamp default current_timestamp, 
    t3 timestamp default '20180627123423', 
    t4 timestamp default current_timestamp on update current_timestamp, 
    t5 timestamp default '20180627123423' on update current_timestamp, 
    t6 timestamp on update current_timestamp 
);

 

结果:

Table: t2
Create Table: CREATE TABLE `t2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `t1` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `t2` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `t3` timestamp NOT NULL DEFAULT '2018-06-27 12:34:23',
  `t4` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `t5` timestamp NOT NULL DEFAULT '2018-06-27 12:34:23' ON UPDATE CURRENT_TIMESTAMP,
  `t6` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

 

转载于:https://www.cnblogs.com/bibiafa/p/9229751.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值