37

MySQL为字段添加默认时间

 4 years ago
source link: https://www.tuicool.com/articles/bUBJNje
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

应用场景:

  • 在数据表中,要记录每条数据是什么时候创建的,不需要应用程序去特意记录,而由数据数据库获取当前时间自动记录创建时间;

  • 在数据库中,要记录每条数据是什么时候修改的,不需要应用程序去特意记录,而由数据数据库获取当前时间自动记录修改时间;

实现方式:

  • 将字段类型设为 TIMESTAMP

  • 将默认值设为 CURRENT_TIMESTAMP

举例应用:

MySQL 脚本实现用例

create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`datalevel` tinyint(1) DEFAULT '1' COMMENT '是否已删除(0删除/1正常)',

ALTER TABLE table_name
ADD COLUMN create_time datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间';
ALTER TABLE table_name
ADD COLUMN update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间';
ALTER TABLE table_name
ADD COLUMN datalevel tinyint(1) DEFAULT '1' COMMENT '是否已删除(0删除/1正常)';

MySQL创建普通索引

ALTER TABLE projectfile ADD INDEX (fileuploadercode, projectid);

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK