mysql created_at/updated_at 自动更新

(1) 插入的时候自动获取当前时间(格式为Y-m-d H:i:s)

ALTER TABLE [table_name] MODIFY created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;

(2) 更新的时候自动获取当前时间(格式为Y-m-d H:i:s)

ALTER TABLE [table_name] MODIFY updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL;

 

实例:

ALTER TABLE tag MODIFY created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
ALTER TABLE tag MODIFY updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL;

--------------

ALTER TABLE tag MODIFY created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
> OK
> 时间: 0.019s

ALTER TABLE tag MODIFY updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL
> Affected rows: 86
> 时间: 0.019s

-------------

  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `deleted_at` timestamp NULL DEFAULT NULL,

 

也可以:

created_at timestamp   NOT NULL   DEFAULT CURRENT_TIMESTAMP ,
updated_at timestamp   NULL   DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
 

你可能感兴趣的:(数据库)