mysql中TIMESTAMP和DATETIME

xiaoxiao2021-02-28  95

一、TIMESTAMP create table test_time ( time1 TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, time2 TIMESTAMP NOT NULL, time3 DATETIME default null, time4 DATETIME default ‘2010-01-01 00:00:00’ );

mysql生成表: CREATE TABLE test_time ( time1 timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, time2 timestamp NOT NULL DEFAULT ‘0000-00-00 00:00:00’, time3 datetime DEFAULT NULL, time4 datetime DEFAULT ‘2010-01-01 00:00:00’ ) ENGINE=InnoDB DEFAULT CHARSET=utf8

1、TIMESTAMP列必须有默认值,默认值可以为“0000-00-00 00:00:00”,但不能为null,如果默认是default null,则mysql自动为设置默认值“0000-00-00 00:00:00”。 2、一个表可以存在多个TIMESTAMP列,但只有一个列会根据数据更新而改变为数据库系统当前值( CURRENT_TIMESTAMP in DEFAULT or ON UPDATE)。mysql> create table test_time ( time1 TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, time2 TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, time3 DATETIME default null, time4 DATETIME default ‘2010-01-01 00:00:00’ ); ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause。 3、TIMESTAMP列的默认值是CURRENT_TIMESTAMP常量值。当纪录数据发生变化的时候,TIMESTAMP列会自动将其值设定为CURRENT_TIMESTAMP。 mysql> select * from test_zxk; +———————+———————+———————+———————+ | time1 | time2 | time3 | time4 | +———————+———————+———————+———————+ | 2017-08-31 14:42:39 | 0000-00-00 00:00:00 | 2017-01-01 00:00:00 | 2017-01-01 00:00:00 | | 2017-08-31 14:43:42 | 0000-00-00 00:00:00 | 2017-01-01 00:00:00 | 2010-01-01 00:00:00 | | 2017-08-31 14:43:56 | 0000-00-00 00:00:00 | NULL | 2017-01-01 00:00:00 | +———————+———————+———————+———————+ 3 rows in set (0.04 sec)

mysql> update test_zxk set time4 = ‘2017-01-01 00:00:01’where time4 =’2017-01-01 00:00:00’ -> ; Query OK, 2 rows affected (0.04 sec) Rows matched: 2 Changed: 2 Warnings: 0

mysql> select * from test_zxk; +———————+———————+———————+———————+ | time1 | time2 | time3 | time4 | +———————+———————+———————+———————+ | 2017-08-31 14:44:53 | 0000-00-00 00:00:00 | 2017-01-01 00:00:00 | 2017-01-01 00:00:01 | | 2017-08-31 14:43:42 | 0000-00-00 00:00:00 | 2017-01-01 00:00:00 | 2010-01-01 00:00:00 | | 2017-08-31 14:44:53 | 0000-00-00 00:00:00 | NULL | 2017-01-01 00:00:01 | +———————+———————+———————+———————+ 4、TIMESTAMP列创建后的格式是: time1 timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 这个语句含义,time1字段未对其设置值时,其默认值是当前时间CURRENT_TIMESTAMP,当纪录更新时候,自动将a字段的值设置为 CURRENT_TIMESTAMP。

二、DATETIME

1、DATETIME列可以设置为多个,默认可为null,可以手动设置其值。 2、DATETIME列可以通过hack方式设定默认值,例如:通过触发器、或者在插入数据时候,将DATETIME字段值设置为now()。

三、综上:一般情况,建表时候,创建时间用datetime,更新时间用timestamp。

转载请注明原文地址: https://www.6miu.com/read-38525.html

最新回复(0)