Set NOW() as Default Value for datetime datatype?

I have two columns in table users namely registerDate and lastVisitDate which consist of datetime data type. I would like to do the following.

  • Set registerDate defaults value to MySQL NOW()
  • Set lastVisitDate default value to 0000-00-00 00:00:00 Instead of null which it uses by default.
  • Because the table already exists and has existing records, I would like to use Modify table. I've tried using the two piece of code below, but neither works.

    ALTER TABLE users MODIFY registerDate datetime DEFAULT NOW()
    ALTER TABLE users MODIFY registerDate datetime DEFAULT CURRENT_TIMESTAMP;
    

    It gives me Error : ERROR 1067 (42000): Invalid default value for 'registerDate'

    Is it possible for me to set the default datetime value to NOW() in MySQL?


    As of MySQL 5.6.5, you can use the DATETIME type with a dynamic default value:

    CREATE TABLE foo (
        creation_time      DATETIME DEFAULT   CURRENT_TIMESTAMP,
        modification_time  DATETIME ON UPDATE CURRENT_TIMESTAMP
    )
    

    Or even combine both rules:

    modification_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    

    Reference:
    http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
    http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html

    Prior to 5.6.5, you need to use the TIMESTAMP data type, which automatically updates whenever the record is modified. Unfortunately, however, only one auto-updated TIMESTAMP field can exist per table.

    CREATE TABLE mytable (
      mydate TIMESTAMP
    )
    

    See: http://dev.mysql.com/doc/refman/5.1/en/create-table.html

    If you want to prevent MySQL from updating the timestamp value on UPDATE (so that it only triggers on INSERT ) you can change the definition to:

    CREATE TABLE mytable (
      mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
    

    I use a trigger as a workaround to set a datetime field to NOW() for new inserts:

    CREATE TRIGGER `triggername` BEFORE INSERT ON  `tablename` 
    FOR EACH ROW 
    SET NEW.datetimefield = NOW()
    

    it should work for updates too

    Answers by Johan & Leonardo involve converting to a timestamp field. Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution. See datetime vs timestamp question.


    我的解决方案

    ALTER TABLE `table_name` MODIFY COLUMN `column_name` TIMESTAMP NOT
    NULL DEFAULT CURRENT_TIMESTAMP;
    
    链接地址: http://www.djcxy.com/p/25116.html

    上一篇: 如何以CSV格式输出MySQL查询结果?

    下一篇: 将NOW()设置为datetime数据类型的默认值?