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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题