建表语句
drop table if exists 'mytable';
create table if not exists 'mytable'{
'id' int(11) not null commnet 'id',
'name' varchar(16) defalut null comment '姓名',
creat_time timestamp default CURRENT_TIMESTAMP comment '创建时间',
update_time timestamp defalut CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP comment '修改时间',
primary key ('id')
}ENGINE=INNODB defalut CHARSET=gbk;
注意点
1 timestamp的时间范围是1970.01.01 0时0分0秒 ———2038.01.19 11:14:07(北京时间),因为timestamp是32位整型,只能存储到这里。解决办法,使用datetime类型,但是要注意了,datetime类型是在mysql5.6.5之后才可以使用的。否则会报invalid default value for “cloum name”
2 使用timestamp创建列create_time和update_time的时候,如果使用类型为timestamp,可能会报错 “Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause”,大致的意思是只可以有一个列可以自动初始化或者是更新。这个是在5.6.5之前那的版本有的问题,所以只要升级mysql版本就可以了,
mysql5.6.5关于这一点的提示
Previously, at most one TIMESTAMP column per table could be automatically
initialized or updated to the current date and time. This restriction has been lifted.
Any TIMESTAMP column definition can have any combination of DEFAULT
CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses.
In addition, these clauses now can be used with DATETIME column definitions. For
more information, see Automatic Initialization and Updating for TIMESTAMP and
DATETIME.
以前,每个表的至多一个时间戳列可以自动初始化或更新为当前日期和时间。该限制
已取消。任何时间戳列定义都可以具有默认current_timestamp和
updatecurrent_timestamp子句的任何组合。此外,这些子句现在可以与DateTime列
定义一起使用。有关详细信息,请参见自动初始化和更新时间戳和日期时间
查询mysql版本的两个常用方法
1 mysql -V (V是大写的)
![](https://img.haomeiwen.com/i19712700/2b7a778de270a314.png)
2 select version();
![](https://img.haomeiwen.com/i19712700/e08999ee4ec44bd0.png)
所以在使用时间类型的时候,多注意到底使用timestamp还是datetime类型,还有mysql的版本问题,尽量使用mysql5.6.5+之后的版本。
追加
如果是已经建立的表,想要添加这两个时间列的话,可以使用navicat直接的额进行一个表的修改的。
添加create_time(根据当前时间戳更新不要勾选)
![](https://img.haomeiwen.com/i19712700/4c798da674188456.png)
添加update_time(根据当前时间戳更新要勾选)
![](https://img.haomeiwen.com/i19712700/9f0ee2f3093ecc77.png)
网友评论