11.3.5 Automatic Initialization and Updating for TIMESTAMP and DATETIME

原文地址:https://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html

As of MySQL 5.6.5, TIMESTAMP and DATETIME columns can be automatically initializated and updated to the current date and time (that is, the current timestamp). Before 5.6.5, this is true only for TIMESTAMP, and for at most one TIMESTAMP column per table. The following notes first describe automatic initialization and updating for MySQL 5.6.5 and up, then the differences for versions preceding 5.6.5.

For any TIMESTAMP or DATETIME column in a table, you can assign the current timestamp as the default value, the auto-update value, or both:

  • An auto-initialized column is set to the current timestamp for inserted rows that specify no value for the column.

  • An auto-updated column is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. An auto-updated column remains unchanged if all other columns are set to their current values. To prevent an auto-updated column from updating when other columns change, explicitly set it to its current value. To update an auto-updated column even when other columns do not change, explicitly set it to the value it should have (for example, set it to CURRENT_TIMESTAMP).

In addition, you can initialize or update any TIMESTAMP column to the current date and time by assigning it a NULLvalue, unless it has been defined with the NULL attribute to permit NULL values.

To specify automatic properties, use the DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMPclauses in column definitions. The order of the clauses does not matter. If both are present in a column definition, either can occur first. Any of the synonyms for CURRENT_TIMESTAMP have the same meaning asCURRENT_TIMESTAMP. These are CURRENT_TIMESTAMP()NOW()LOCALTIMELOCALTIME()LOCALTIMESTAMP, and LOCALTIMESTAMP().

Use of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP is specific to TIMESTAMP andDATETIME. The DEFAULT clause also can be used to specify a constant (nonautomatic) default value; for example,DEFAULT 0 or DEFAULT '2000-01-01 00:00:00'.

Note

The following examples use DEFAULT 0, a default that can produce warnings or errors depending on whether strict SQL mode or the NO_ZERO_DATE SQL mode is enabled. Be aware that the TRADITIONAL SQL mode includes strict mode and NO_ZERO_DATE. See Section 5.1.7, “Server SQL Modes”.

TIMESTAMP or DATETIME column definitions can specify the current timestamp for both the default and auto-update values, for one but not the other, or for neither. Different columns can have different combinations of automatic properties. The following rules describe the possibilities:

  • With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP, the column has the current timestamp for its default value and is automatically updated to the current timestamp.

    1. CREATE TABLE t1 (
    2. ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    3. dt DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    4. );
  • With a DEFAULT clause but no ON UPDATE CURRENT_TIMESTAMP clause, the column has the given default value and is not automatically updated to the current timestamp.

    The default depends on whether the DEFAULT clause specifies CURRENT_TIMESTAMP or a constant value. WithCURRENT_TIMESTAMP, the default is the current timestamp.

    1. CREATE TABLE t1 (
    2. ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    3. dt DATETIME DEFAULT CURRENT_TIMESTAMP
    4. );

    With a constant, the default is the given value. In this case, the column has no automatic properties at all.

    1. CREATE TABLE t1 (
    2. ts TIMESTAMP DEFAULT 0,
    3. dt DATETIME DEFAULT 0
    4. );
  • With an ON UPDATE CURRENT_TIMESTAMP clause and a constant DEFAULT clause, the column is automatically updated to the current timestamp and has the given constant default value.

    1. CREATE TABLE t1 (
    2. ts TIMESTAMP DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP,
    3. dt DATETIME DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP
    4. );
  • With an ON UPDATE CURRENT_TIMESTAMP clause but no DEFAULT clause, the column is automatically updated to the current timestamp but does not have the current timestamp for its default value.

    The default in this case is type dependent. TIMESTAMP has a default of 0 unless defined with the NULL attribute, in which case the default is NULL.

    1. CREATE TABLE t1 (
    2. ts1 TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- default 0
    3. ts2 TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP -- default NULL
    4. );

    DATETIME has a default of NULL unless defined with the NOT NULL attribute, in which case the default is 0.

    1. CREATE TABLE t1 (
    2. dt1 DATETIME ON UPDATE CURRENT_TIMESTAMP, -- default NULL
    3. dt2 DATETIME NOT NULL ON UPDATE CURRENT_TIMESTAMP -- default 0
    4. );

TIMESTAMP and DATETIME columns have no automatic properties unless they are specified explicitly, with this exception: By default, the first TIMESTAMP column has both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP if neither is specified explicitly. To suppress automatic properties for the first TIMESTAMPcolumn, use one of these strategies:

  • Enable the explicit_defaults_for_timestamp system variable. If this variable is enabled, the DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses that specify automatic initialization and updating are available, but are not assigned to any TIMESTAMP column unless explicitly included in the column definition.

  • Alternatively, if explicit_defaults_for_timestamp is disabled (the default), do either of the following:

    • Define the column with a DEFAULT clause that specifies a constant default value.

    • Specify the NULL attribute. This also causes the column to permit NULL values, which means that you cannot assign the current timestamp by setting the column to NULL. Assigning NULL sets the column to NULL.

Consider these table definitions:

  1. CREATE TABLE t1 (
  2. ts1 TIMESTAMP DEFAULT 0,
  3. ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  4. ON UPDATE CURRENT_TIMESTAMP);
  5. CREATE TABLE t2 (
  6. ts1 TIMESTAMP NULL,
  7. ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  8. ON UPDATE CURRENT_TIMESTAMP);
  9. CREATE TABLE t3 (
  10. ts1 TIMESTAMP NULL DEFAULT 0,
  11. ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  12. ON UPDATE CURRENT_TIMESTAMP);

The tables have these properties:

  • In each table definition, the first TIMESTAMP column has no automatic initialization or updating.

  • The tables differ in how the ts1 column handles NULL values. For t1ts1 is NOT NULL and assigning it a value ofNULL sets it to the current timestamp. For t2 and t3ts1 permits NULL and assigning it a value of NULL sets it toNULL.

  • t2 and t3 differ in the default value for ts1. For t2ts1 is defined to permit NULL, so the default is also NULL in the absence of an explicit DEFAULT clause. For t3ts1 permits NULL but has an explicit default of 0.

If a TIMESTAMP or DATETIME column definition includes an explicit fractional seconds precision value anywhere, the same value must be used throughout the column definition. This is permitted:

  1. CREATE TABLE t1 (
  2. ts TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)
  3. );

This is not permitted:

  1. CREATE TABLE t1 (
  2. ts TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(3)
  3. );

Automatic Timestamp Properties Before MySQL 5.6.5

Before MySQL 5.6.5, support for automatic initialization and updating is more limited:

  • DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP cannot be used with DATETIME columns.

  • DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP can be used with at most one TIMESTAMPcolumn per table. It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.

You can choose whether to use these properties and which TIMESTAMP column should have them. It need not be the first one in a table that is automatically initialized or updated to the current timestamp. To specify automatic initialization or updating for a different TIMESTAMP column, you must suppress the automatic properties for the first one, as previously described. Then, for the other TIMESTAMP column, the rules for the DEFAULT and ON UPDATE clauses are the same as for the first TIMESTAMP column, except that if you omit both clauses, no automatic initialization or updating occurs.

TIMESTAMP Initialization and the NULL Attribute

By default, TIMESTAMP columns are NOT NULL, cannot contain NULL values, and assigning NULL assigns the current timestamp. To permit a TIMESTAMP column to contain NULL, explicitly declare it with the NULL attribute. In this case, the default value also becomes NULL unless overridden with a DEFAULT clause that specifies a different default value. DEFAULT NULL can be used to explicitly specify NULL as the default value. (For a TIMESTAMPcolumn not declared with the NULL attribute, DEFAULT NULL is invalid.) If a TIMESTAMP column permits NULLvalues, assigning NULL sets it to NULL, not to the current timestamp.

The following table contains several TIMESTAMP columns that permit NULL values:

  1. CREATE TABLE t
  2. (
  3. ts1 TIMESTAMP NULL DEFAULT NULL,
  4. ts2 TIMESTAMP NULL DEFAULT 0,
  5. ts3 TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP
  6. );

TIMESTAMP column that permits NULL values does not take on the current timestamp at insert time except under one of the following conditions:

In other words, a TIMESTAMP column defined to permit NULL values auto-initializes only if its definition includesDEFAULT CURRENT_TIMESTAMP:

  1. CREATE TABLE t (ts TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP);

If the TIMESTAMP column permits NULL values but its definition does not include DEFAULT CURRENT_TIMESTAMP, you must explicitly insert a value corresponding to the current date and time. Suppose that tables t1 and t2 have these definitions:

  1. CREATE TABLE t1 (ts TIMESTAMP NULL DEFAULT '0000-00-00 00:00:00');
  2. CREATE TABLE t2 (ts TIMESTAMP NULL DEFAULT NULL);

To set the TIMESTAMP column in either table to the current timestamp at insert time, explicitly assign it that value. For example:

  1. INSERT INTO t1 VALUES (NOW());
  2. INSERT INTO t2 VALUES (CURRENT_TIMESTAMP);

mysql 表设计时的update_time自动更新的更多相关文章

  1. EF5修改edmx表结构保存后不自动更新tt (转)

    http://blog.csdn.net/panderman/article/details/8172968 不知道这算不算一个bug,当你新建一个从数据库生成的edmx时,他能正确的生成所有的tt文 ...

  2. 【JDBC】向数据表插入数据时,自动获取生成的主键

    数据表设计时,一般都会有一个主键(Key)(自己指定),有时也可以使用联合主键: 有许多数据库提供了隐藏列为表中的每行记录分配一个唯一键值(如:rowid): 当我们没有指定哪一列作为主键key时,数 ...

  3. mysql每次update数据,自动更新对应表中时间字段

    mysql 已经创建完成表的情况下, 使得其中的时间字段 在每次 uodate 数据的时候 自动更新事件, 运行如下sql ALTER TABLE tab_name MODIFY COLUMN upd ...

  4. Mysql 添加 create_time, update_time 创建时间 更新时间 自动更新

    # 添加 创建 更新 时间字段 ALTER TABLE `表名` ADD COLUMN `create_time`  datetime NOT NULL DEFAULT CURRENT_TIMESTA ...

  5. [mysql] timestamp自动更新和初始化

    1.概述 在我们设计表的时候,考虑将行数据的创建时间和最后更新时间记录下来是很好的实践.尤其是可能需要做数据同步或者对数据新鲜度有要求的表.举些应用场景,更新距上次更新超过2小时的行数据,或者是将一个 ...

  6. MySQL的timestamp类型自动更新问题

    今天建了一个表,里面有一个列是timestamp类型,我本意是在数据更新时,这个字段的时间能自动更新.岂知对这个类型的值还不甚了解,导致出错.发现这个字段只是在这行数据建立的时候有值,在更新的却无变化 ...

  7. Mysql自动更新字段时间

    Mysql中更新某天数据可设置该条数据中的某个字段自动更新 ALTER TABLE `表名` MODIFY `字段名` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON U ...

  8. Mysql中,update语句引起的时间戳自动更新问题

    前几天遇到一个奇怪的问题. 在Mysql数据库中有一张表,表中有一个字段是timestamp类型的.我在update别的字段时,这个timestamp字段的时间会自动更新为当前时间. 后来发现,是My ...

  9. MySQL表内更新时,自动记录时间

    1.创建表: create table test_time(id int primary key not null,status  varchar(24),create_time datetime d ...

随机推荐

  1. 怎样使用纯CSS3创建一个简单的五角星图形

    我们能够使用SVG.Canvas.CSS3或者背景图片来实现五角星图案及其悬停效果. CSS3引入的伪元素和变换特性使得实现五角星图形很easy,而且能够结合渐变实现更为美丽的效果.因此使用图片实现五 ...

  2. session和cookie详解

    摘要:虽然session机制在web应用程序中被采用已经很长时间了,但是仍然有很多人不清楚session机制的本质,以至不能正确的应用这一 技术.本文将详细讨论session的工作机制并且对在Java ...

  3. 异步FIFO及verilog原码

    这几天看了Clifford E. Cummings的两篇大作<Simulation and Synthesis Techniques for Asynchronous FIFO Design&g ...

  4. BZOJ2020: [Usaco2010 Jan]Buying Feed II

    [传送门:BZOJ2020] 简要题意: 约翰开车回家,遇到了双十一节,那么就顺路买点饲料吧.回家的路程一共有E 公里,这一路上会经过N 家商店,第i 家店里有Fi 吨饲料,售价为每吨Ci 元.约翰打 ...

  5. mybatis :与Spring MVC 的集成

    用mybatis与Spring mvc 的方式集成起来,源码在本文结尾处下载.主要有以下几个方面的配置1. web.xml 配置 spring dispatchservlet ,比如为:mvc-dis ...

  6. beego简单的验证码实现以及验证

    /** * 程序 */package controllers import (    "github.com/astaxie/beego"    "github.com/ ...

  7. JWT Authentication Tutorial: An example using Spring Boot--转

    原文地址:http://www.svlada.com/jwt-token-authentication-with-spring-boot/ Table of contents: Introductio ...

  8. docker升级&加速器配置

    默认使用yum或者apt安装的docker版本较老,可以通过以下方式进行升级: 1.卸载旧版本 [root@CentOS702 ~]# centos 7.3卸载docker[root@CentOS70 ...

  9. 无闻go编程基础笔记

    Go语言做Web编程非常方便,并且在开发效率和程序运行效率方面都非常优秀.相比于Java,其最大的优势就是简便易用,而相比于PHP,它最大的优势就是性能好. (go做web)推荐Gorilla的库,里 ...

  10. jquery autocomplete文本自己主动补全

    文本自己主动补全功能确实非常有用. 先看下简单的效果:(样式不咋会写) 以下介绍几种: 1:jqery-actocomplete.js 这个网上有个写好的实例,上面挺具体的,能够下来执行下就清楚了就不 ...