Mysql中设置默认时间为当前值

文章转载:Mysql中设置默认时间为当前值

1、直接在创建表时添加该列并声明默认值,如下:

CREATE TABLE `table1` (
  `id` int(11) NOT NULL,
  `createtime` timestamp NULL default CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

若是手动创建表,使字段类型设为timestamp,在默认值处输入now()即可

2、在现有表中添加新列

ALTER TABLE table1
ADD COLUMN  `createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP

3、 修改某一列为格式并添加默认值

alter table table1  MODIFY createTime timestamp not NULL DEFAULT CURRENT_TIMESTAM

4、 修改某一列为时间格式并添加默认值(将列名为name的改为username,类型也可以同时修改)

alter table table1  CHANGE name username varchar(12) not NULL default 'vv' 

5、 修改数据表时,该列时间能自动切换为当前时间

CREATE TABLE `table1` (
  `id` int(11) NOT NULL,
  `createtime` timestamp not NULL default CURRENT_TIMESTAMP 
               on update CURRENT_TIMESTAMP 
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

直接用客户端操作
Mysql中设置默认时间为当前值_第1张图片

ps:修改字段类型为 timestamp 时,需要注意的是,一张表 只能有一个 timestamp 类型的字段 可以有多个timestamp 类型,但是只能有一个字段的默认值设置为CURRENT_TIMESTAMP ,否则会报 Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause 异常。

你可能感兴趣的:(mysql)