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.

    CREATE TABLE t1 (ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,dt DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    );
    
  • 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.

    CREATE TABLE t1 (ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,dt DATETIME DEFAULT CURRENT_TIMESTAMP
    );
    

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

    CREATE TABLE t1 (ts TIMESTAMP DEFAULT 0,dt DATETIME DEFAULT 0
    );
    
  • 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.

    CREATE TABLE t1 (ts TIMESTAMP DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP,dt DATETIME DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP
    );
    
  • 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.

    CREATE TABLE t1 (ts1 TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,     -- default 0ts2 TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP -- default NULL
    );
    

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

    CREATE TABLE t1 (dt1 DATETIME ON UPDATE CURRENT_TIMESTAMP,         -- default NULLdt2 DATETIME NOT NULL ON UPDATE CURRENT_TIMESTAMP -- default 0
    );
    

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:

CREATE TABLE t1 (ts1 TIMESTAMP DEFAULT 0,ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMPON UPDATE CURRENT_TIMESTAMP);
CREATE TABLE t2 (ts1 TIMESTAMP NULL,ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMPON UPDATE CURRENT_TIMESTAMP);
CREATE TABLE t3 (ts1 TIMESTAMP NULL DEFAULT 0,ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMPON 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:

CREATE TABLE t1 (ts TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)
);

This is not permitted:

CREATE TABLE t1 (ts TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(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:

CREATE TABLE t
(ts1 TIMESTAMP NULL DEFAULT NULL,ts2 TIMESTAMP NULL DEFAULT 0,ts3 TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP
);

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

  • Its default value is defined as CURRENT_TIMESTAMP and no value is specified for the column

  • CURRENT_TIMESTAMP or any of its synonyms such as NOW() is explicitly inserted into the column

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

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:

CREATE TABLE t1 (ts TIMESTAMP NULL DEFAULT '0000-00-00 00:00:00');
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:

INSERT INTO t1 VALUES (NOW());
INSERT INTO t2 VALUES (CURRENT_TIMESTAMP);

转载于:https://www.cnblogs.com/davidwang456/p/4747069.html

mysql 表设计时的update_time自动更新相关推荐

  1. excel自动排班表_Excel数据分析-如何制作自动更新的数据透视表

    数据透视表是我们工作中一个非常强大的数据汇总分析功能,大家一定会遇到这样的问题,就是数据源如果每天或者经常性需要更新的话,那么我们的数据透视表就要在每次更新后重新选择数据源,如何能让数据源自动更新呢? ...

  2. 修改注册表,关闭window系统自动更新服务

    运行"regedit",打开注册表编辑器,定位到 "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WaaSMe ...

  3. jdbc 3种获得mysql插入数据的自增字段值的方法_【JDBC】向数据表插入数据时,自动获取生成的主键...

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

  4. MySQL自动更新当前时间戳

    1. 问题 碰到一个奇怪的问题,一个业务表当更新了其中几行后,这几行对应的列created_at(DATETIME)自动更新为当前时间. 2. 排查 第一感觉想到触发器,排查表并未有触发器. 打开表设 ...

  5. mysql 优惠卷表设计_这些年MySQL表设计踩过的坑!

    本文首发于个人微信公众号<andyqian>,期待你的关注! 前言 有朋友在后台留言.希望我能说说我在数据库表设计时踩过的坑.那么,我们今天就来聊聊我在数据库表设计时踩过的坑,以及现在对数 ...

  6. java MySQL表的约束与数据库设计 详解

    1.DQL 数据查询语言 在上一篇博文中,我们已经讲述了部分数据查询语句,在此我们再次对其进行补充. 1.1 排序 通过ORDAR BY 语句,可以将查询出来的结果进行排序.(排除只是一种现实的方式, ...

  7. 无法输入文字,电脑变慢,禁止IE浏览器自动更新怎么办,进来这里有方法!

    目录 无法输入文字如何解决 电脑变慢 禁止IE浏览器自动更新 方法一: 方法二: 无法输入文字如何解决 原因:IE网页mshtmled.dll组件被破坏,解决方法是 开始 运行 regsvr32 ms ...

  8. 如何有效的关闭Win10/ win 11 自动更新? 方法最全

    提示:想寻找Win10关闭自动更新方法?win11,试过,方法通用,我就用win10 为例子来讲,对于Win10用户经常会遇到系统提示更新,很多用户都因其而烦恼.有时选择拒绝更新,系统会一直不停的提示 ...

  9. MySQL~表的设计练习(食堂管理系统、车辆违章系统、宿舍管理系统、考勤系统)

    目录 食堂管理系统 车辆违章系统 宿舍管理系统 考勤系统 表的设计有1对1.1对多.多对多三种设计方式,根据不同的业务需求,设计出不同的表关系,关于表的设计在之前的博客中有所涉及,具体请点击查看:表的 ...

最新文章

  1. 纯数学教程 Page 203 例XLI (1)
  2. Android App监听软键盘按键的三种方式
  3. nn.Conv2d中padding详解【pytorch学习】
  4. Network 【TCP/IP 四层模型】
  5. 游戏中DDA算法和Bresenham算法的应用
  6. Express Session 的基本使用
  7. python获取每月的最后一天_关于日期:使用Python获取本月的最后一天
  8. 测试标准I/O缓冲的代码,
  9. Android基础篇1:Activity
  10. 华硕老毛子(Padavan)——校园网锐捷(Ruijie)认证路由限制解决方案(锐捷(Ruijie)认证+赛尔认证)
  11. 在电力行业中高频开关电源中起什么作用?
  12. 泳池水质监控PH温度浑浊度测量_基于STC89C51单片机
  13. 自适应布局-使用css3函数clac()
  14. redis基数树rax源码分析(1)
  15. 中国通史—秦的统一与政策
  16. 容易被误解的overflow:hidden
  17. EndNote7.x/9.x 中基于国家标准的 EndNote 输出样式模板使用说明
  18. storm trident mysql_Trident-MySQL
  19. APP在电脑模拟器上完美运行,真机运行时闪退现象记录
  20. python调用百度api接口_python调用百度API

热门文章

  1. php获取http头信息,php如何获取http头信息
  2. python打印自动换行如何解决_解决python DataFrame 打印结果不换行问题
  3. c# socket接收字符串_Python高级编程之 Socket 编程
  4. mongodb更新数据,查找相同的id,有重复的,就更新。
  5. pandas读取剪切板
  6. 双任务时间片运行原理
  7. 电脑主板接口_POWER SW、RESET SW、POWER LED、HDD LED电脑主板跳线怎么接?
  8. Linux源码手机,Linux操作系统源代码详细分析
  9. 易语言 mysql 卡死_易语言操作MYsql 所有课程停发
  10. 解决Cannot convert a symbolic Tensor (lstm/strided_slice:0) to a numpy array.