一、时间取值范围
datetime类型取值范围:1000-01-01 00:00:00 到 9999-12-31 23:59:59
timestamp类型取值范围:1970-01-01 00:00:00 到 2037-12-31 23:59:59
timestamp类型具有自动初始化和自动更新的特性。
二、timestamp自动更新的机制
2.1 下面列举下那些情况会自动更新
第一个timestamp的字段,不指定是否为空默认为not null,
下方test1和test2中create_date 都会自动更新
create table test1 (
id int primary key ,
create_date timestamp ,
update_date timestamp null default null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
create table test2 (
id int primary key ,
create_date timestamp not null ,
update_date timestamp null default null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
还有一种情况会自动更新:
指定更新是自动更新eg: ON UPDATE CURRENT_TIMESTAMP
下面举一个例子:允许为空的时候,指定更新时自动更新
create table test5 (
id int primary key ,
create_date timestamp null on update current_timestamp,
update_date timestamp null default null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
test5:插入的时候,不会插入时间
更新的时候,会自动更新create_date
2.2 下面列举下哪些情况不会自动更新
第一个timestamp,指定允许为null,或者指定默认值,not null default CURRENT_TIMESTAMP
create table test3 (
id int primary key ,
create_date timestamp null,
update_date timestamp null default null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
create table test4 (
id int primary key ,
create_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
update_date timestamp null default null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
允许为null,则插入和更新都不会自动插入该值
不允许为null,有默认值,第一次插入的时候会自动插入 默认值,更新的时候不会在自动更新该字段的值