您的位置:首页 > 数据库 > MySQL

MySQL数据类型之日期和时间类型

2017-11-21 11:57 507 查看


截图于菜鸟网络。

注意几点:

1、TIMESTAMP 实际存储的值为‘1970-01-01 00:00:00’到当前时间的毫秒数;

2、MySQL5.5及之前版本,DATETIME不能设置函数式默认值,DATETIME 默认值设置now()是无效的,只能通过触发器等来实现;想设置默认值,只能使用TIMESTAMP类型,默认值设置为:CURRENT_TIMESTAMP。

     但从5.6.5及之后的版本,DATETIME类型字段也可以用DEFAULT
CURRENT_TIMESTAMP子句设置默认值了。

    上述设置默认值的问题,是借鉴网友的,因为我的版本是5.7.18,没有根据不同版本验证,写在这儿就是提醒一下默认值设置时要根据自身版本去验证,以免出错;

在此列出网友对于版本不同做的一些验证:

MySQL版本区别5.5与5.7之DEFAULT CURRENT_TIMESTAMP

MySQL5.6时间类型timestamp和datetime有了重大改变

mysql设置datetime默认值为now(但不支持)

MySQL datetime数据类型设置当前时间为默认值

3、MySQL设置字段自动获取创建时间和更新时间(我的mysql 版本'5.7.18-log')

CREATE table test1(id int,
create_time timestamp null default current_timestamp comment '创建时间',
update_time timestamp null default current_timestamp on update current_timestamp comment '更新时间'
);


也可以用datetime实现:

CREATE table test1(id int,
create_time datetime null default current_timestamp comment '创建时间',
update_time datetime null default now() on update current_timestamp comment '更新时间'
);


还需要注意的一点是,如果执行了update操作,但实际数据没有更新时,更新时间update_time是不会更新的。
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

与时间和日期有关的函数:

1、now()、current_timestamp()、sysdate()

这些函数都是返回当前的系统时间,区别主要是now、current_timestamp返回的是执行当前sql语句时的时间;sysdate返回的是执行当前函数时的时间。

select now(),current_timestamp(), sysdate(),
sleep(3),
now(),current_timestamp(), sysdate();


结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息