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

后端 未结 26 2705
野的像风
野的像风 2020-11-22 01:55

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 tha

26条回答
  •  庸人自扰
    2020-11-22 02:33

    Take for instance If I had a table named 'site' with a created_at and an update_at column that were both DATETIME and need the default value of now, I could execute the following sql to achieve this.

    ALTER TABLE `site` CHANGE `created_at` `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
    
    ALTER TABLE `site` CHANGE `created_at` `created_at` DATETIME  NULL DEFAULT NULL;
    
    ALTER TABLE `site` CHANGE `updated_at` `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
    
    ALTER TABLE `site` CHANGE `updated_at` `updated_at` DATETIME NULL DEFAULT  NULL;
    

    The sequence of statements is important because a table can not have two columns of type TIMESTAMP with default values of CUREENT TIMESTAMP

提交回复
热议问题