CREATE table of date type and use its default value as CURRENT_DATE on MySQL

后端 未结 2 1943
我在风中等你
我在风中等你 2021-01-24 01:25

I tried running below code in sql command, but the code line start_date date DEFAULT CURRENT_DATE had issues, got no idea why. I needed only date.

But if I

相关标签:
2条回答
  • 2021-01-24 01:25

    In this way I was able to use CURRENT_DATE function. This code is 100% tested. Note, date value of that instance of point when new row is added is saved.

    I used following, SQL first:

    CREATE TABLE advertisement (
      id int(11) NOT NULL AUTO_INCREMENT,
      summary text DEFAULT NULL,
      featured_image varchar(50) DEFAULT NULL,
      start_date date DEFAULT NULL,
      end_date date NOT NULL,
      link text DEFAULT NULL,
      added_date datetime DEFAULT CURRENT_TIMESTAMP,
      updated_date datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
    )
    

    and then during adding SQL I used query as

    INSERT INTO `advertisement` SET
    start_date=CURRENT_DATE(),
    end_date='2018-04-02',
    added_date='2018-03-01 00:10:33'
    

    Thank you all for your suggestion.

    0 讨论(0)
  • 2021-01-24 01:28

    The documentation is quite clear that this works for datetime columns but not date columns:

    This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. The exception is that you can specify CURRENT_TIMESTAMP as the default for TIMESTAMP and DATETIME columns.

    If you really have your heart set on ignoring the time component, you will have to use a trigger to set the value, rather than a default constraint.

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