7*4 2008-10-03 20:24 采纳率: 50%
浏览 4783
已采纳

如何设置 MySQL 日期时间列的默认值?

如何设置MySQL Datetime列的默认值? 在SQL Server中是 getdate(). MySQL的等效功能是什么? 如果这是一个原因的话,那么我来使用MySQL5.x尝试一下。

转载于:https://stackoverflow.com/questions/168736/how-do-you-set-a-default-value-for-a-mysql-datetime-column

  • 写回答

24条回答

  • 喵-见缝插针 2008-10-03 20:48
    关注

    IMPORTANT EDIT: It is now possible to achieve this with DATETIME fields since MySQL 5.6.5, take a look at the other post below...

    Previous versions can't do that with DATETIME...

    But you can do it with TIMESTAMP:

    mysql> create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> desc test;
    +-------+-------------+------+-----+-------------------+-------+
    | Field | Type        | Null | Key | Default           | Extra |
    +-------+-------------+------+-----+-------------------+-------+
    | str   | varchar(32) | YES  |     | NULL              |       | 
    | ts    | timestamp   | NO   |     | CURRENT_TIMESTAMP |       | 
    +-------+-------------+------+-----+-------------------+-------+
    2 rows in set (0.00 sec)
    
    mysql> insert into test (str) values ("demo");
    Query OK, 1 row affected (0.00 sec)
    
    mysql> select * from test;
    +------+---------------------+
    | str  | ts                  |
    +------+---------------------+
    | demo | 2008-10-03 22:59:52 | 
    +------+---------------------+
    1 row in set (0.00 sec)
    
    mysql>
    

    **CAVEAT: IF you define a column with CURRENT_TIMESTAMP ON as default, you will need to ALWAYS specify a value for this column or the value will automatically reset itself to "now()" on update. This means that if you do not want the value to change, your UPDATE statement must contain "[your column name] = [your column name]" (or some other value) or the value will become "now()". Weird, but true. I hope this helps. I am using 5.5.56-MariaDB **

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(23条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!