MySQL中默认值中用时间函数的问题

今天在上课的时候在测试MSSQL建表的时候 注册时间默认值用getdate()可以获取插入值时候的时间create table temp( id int PRIMARY key, in_time datetime NOT NULL default getdate() )

但是在MYSQL建表练习的时候不能用now()进行对应的做法:

create table temp(    id int PRIMARY key,    in_time datetime NOT NULL default now() )

却不行,最后发现MYSQL中有个数据类型:时间戳timestamp,这个类型如其意思就像邮戳一样在更改信内容时时邮戳上的时间不会改变,这种类型用来定义注册时间再好不过了。

做了具体的改动:

create table temp(    id int PRIMARY key,    in_time timestamp NOT NULL default now() )

不过建议用这种做法:

create table temp(    id int PRIMARY key,    in_time timestamp NOT NULL default CURRENT_TIMESTAMP )

如果想在更新表内内容时候默认的时间戳也会便会则在穿件时间字段时候后面加on update CURRENT_TIMESTAMP 即可:

create table temp(    id int PRIMARY key,    in_time timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP )

如果时间戳用在一个固定不变的时间上,比如用户的注册时间上那再好不过了,不过这种在数据库中对时间能否因为需求的变更而变更显得相当麻烦,因为在不稳定的需求过程中你修改数据库表结构的代价毕竟比在程序里加一句update in_time(就是更新时间,具体问题具体写法)更大。

程序设计,按严格的执行顺序和需求来。

原文地址:https://www.cnblogs.com/fedro/p/4351824.html