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

后端 未结 26 2179
野的像风
野的像风 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:27

    Working fine with MySQL 8.x

    CREATE TABLE `users` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
          `dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`id`),
          UNIQUE KEY `mobile_UNIQUE` (`mobile`)
        ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
    
    0 讨论(0)
  • 2020-11-22 02:28

    For all who use the TIMESTAMP column as a solution i want to second the following limitation from the manual:

    http://dev.mysql.com/doc/refman/5.0/en/datetime.html

    "The TIMESTAMP data type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. It has varying properties, depending on the MySQL version and the SQL mode the server is running in. These properties are described later in this section. "

    So this will obviously break your software in about 28 years.

    I believe the only solution on the database side is to use triggers like mentioned in other answers.

    0 讨论(0)
  • 2020-11-22 02:29

    You can use now() to set the value of a datetime column, but keep in mind that you can't use that as a default value.

    0 讨论(0)
  • 2020-11-22 02:30

    I think it simple in mysql since mysql the inbuilt function called now() which gives current time(time of that insert).

    So your query should look like similarly

    CREATE TABLE defaultforTime(
        `creation_time`     DATETIME DEFAULT CURRENT_TIMESTAMP,
        `modification_time` DATETIME default now()
    );
    

    Thank you.

    0 讨论(0)
  • 2020-11-22 02:31

    For all those who lost heart trying to set a default DATETIME value in MySQL, I know exactly how you feel/felt. So here is is:

    ALTER TABLE  `table_name` CHANGE `column_name` DATETIME NOT NULL DEFAULT 0
    

    Carefully observe that I haven't added single quotes/double quotes around the 0

    I'm literally jumping after solving this one :D

    0 讨论(0)
  • 2020-11-22 02:32

    Here is how to do it on MySQL 5.1:

    ALTER TABLE `table_name` CHANGE `column_name` `column_name` 
    TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
    

    I have no clue why you have to enter the column name twice.

    0 讨论(0)
提交回复
热议问题