Didn"t forge 2008-10-03 20:24 采纳率: 25%
浏览 1489
已采纳

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

How do you set a default value for a MySQL Datetime column?

In SQL Server it's getdate(). What is the equivalant for MySQL? I'm using MySQL 5.x if that is a factor.

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

  • 写回答

24条回答 默认 最新

  • 狐狸.fox 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条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题