MySQL timestamp 类型的使用

timestamp类型用来存储时间,它其实也就是个时间戳,只是显示出来为时间格式

timestamp可以在数据插入和更新的时候自动插入当前时间

1.默认情况下,timestamp字段在表插入和更新的时候都会自动更新时间

drop table if exists profile;
create table profile
(
	id int auto_increment
		primary key,
	age smallint(6) default 0 not null,
	add_time timestamp not null
);

和下面的效果一样

drop table if exists profile;
create table profile
(
	id int auto_increment
		primary key,
	age smallint(6) default 0 not null,
	add_time timestamp not null default current_timestamp on update current_timestamp
);

2.如果只想timestamp字段在插入的时候写入当前时间,以后修改不再更改

drop table if exists profile;
create table profile
(
	id int auto_increment
		primary key,
	age smallint(6) default 0 not null,
	add_time timestamp not null default current_timestamp
);

3.在插入的时候给个0值,在修改的时候更新当前时间

drop table if exists profile;
create table profile
(
	id int auto_increment
		primary key,
	age smallint(6) default 0 not null,
	add_time timestamp not null on update current_timestamp
);

4.插入的时候给个默认值,修改的时候更新时间

drop table if exists profile;
create table profile
(
	id int auto_increment primary key,
	age smallint(6) default 0 not null,
	add_time timestamp not null default '2018-08-13 13:08:08' on update current_timestamp
);

关于timestamp的详细介绍和与datatime的对比请参考

https://www.cnblogs.com/panxuejun/p/6134993.html

https://blog.csdn.net/shubingzhuoxue/article/details/52606645

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值