zoukankan      html  css  js  c++  java
  • mysql建表设置两个默认CURRENT_TIMESTAMP的技巧

    转载:http://blog.163.com/user_zhaopeng/blog/static/166022708201252323942430/

     

    业务场景:

    例如用户表,我们需要建一个字段是创建时间, 一个字段是更新时间.

    解决办法可以是指定插入时间,也可以使用数据库的默认时间.

    在mysql中如果设置两个默认CURRENT_TIMESTAMP,会出现这样的错误.

    ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause.

    错误的建表语句:

    CREATE TABLE `db1`.`sms_queue` (
      `Id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
      `Message` VARCHAR(160) NOT NULL DEFAULT 'Unknown Message Error',
      `CurrentState` VARCHAR(10) NOT NULL DEFAULT 'None',
      `Phone` VARCHAR(14) DEFAULT NULL,
      `Created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `LastUpdated` TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP,
      `TriesLeft` tinyint NOT NULL DEFAULT 3,
      PRIMARY KEY (`Id`)
    )
    ENGINE = InnoDB;

    解决办法,可以使用触发器或者其他,在此还是使用数据库的方式.

    建表语句:

    create table test_table(
      id integer not null auto_increment primary key,
      stamp_created timestamp default '0000-00-00 00:00:00',
      stamp_updated timestamp default now() on update now()
    );

    测试:

     mysql> insert into test_table(stamp_created, stamp_updated) values(null, null); 
    Query OK, 1 row affected (0.06 sec)

    mysql> select * from t5;
    +----+---------------------+---------------------+
    | id | stamp_created | stamp_updated |
    +----+---------------------+---------------------+
    | 2 | 2009-04-30 09:44:35 | 2009-04-30 09:44:35 |
    +----+---------------------+---------------------+
    2 rows in set (0.00 sec) mysql> update test_table set id = 3 where id = 2; Query OK, 1 row affected (0.05 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from test_table;+----+---------------------+---------------------+| id | stamp_created | stamp_updated | +----+---------------------+---------------------+ | 3 | 2009-04-30 09:44:35 | 2009-04-30 09:46:59 | +----+---------------------+---------------------+ 2 rows in set (0.00 sec)
    解决办法是在stackoverflow看到的,原文网址:

    http://stackoverflow.com/questions/267658/having-both-a-created-and-last-updated-timestamp-columns-in-mysql-4-0

  • 相关阅读:
    PHP数组
    java中线程池的几种实现方式
    JAVA是是如何处理字符的。
    byte范围及8种常见数据类型
    对Spring 及SpringMVC的理解
    Nginx+Tomcat搭建负载均衡
    nginx + tomcat配置负载均衡
    Java并发编程:Lock
    Java内部类详解
    奇怪的Java题:为什么1000 == 1000返回为False,而100 == 100会返回为True?
  • 原文地址:https://www.cnblogs.com/yanduanduan/p/5369325.html
Copyright © 2011-2022 走看看