我們是否可以在mysql中,將Date字段的默認(rèn)值設(shè)置為CURRENT_DATE(當(dāng)前日期)?
答案是8.0之前不可以,8.0.13之后可以。
比如在5.7版本中使用如下sql創(chuàng)建表,將會(huì)提示語法錯(cuò)誤:
CREATE?TABLE?`t_order`?(
??`id`?bigint?NOT?NULL?AUTO_INCREMENT?COMMENT?'主鍵',
??`create_time`?date?DEFAULT?(curdate()),
??PRIMARY?KEY?(`id`)
)?ENGINE=InnoDB?DEFAULT?CHARSET=utf8mb4;
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(curdate()), PRIMARY KEY (id
) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4' at line 3
官方文檔中,有如下描述:
?With one exception, the default value specified in a DEFAULT clause must be a literal constant; it cannot be a function or an expression. 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, for TIMESTAMP and DATETIME columns, you can specify CURRENT_TIMESTAMP as the default. See Section 11.2.5, “Automatic Initialization and Updating for TIMESTAMP and DATETIME”.
文檔地址:https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html
Date字段不能指定默認(rèn)值now()或者CURRENT_DATE,但是我們可以使用TIMESTAMP或者DATETIME字段,指定默認(rèn)值為CURRENT_TIMESTAMP。
但是從8.0.13版本開始可以指定DATE的默認(rèn)值為的CURRENT_DATE。
需要注意的是指定CURRENT_DATE為默認(rèn)值時(shí),需要用括號(hào)()?包裹住CURRENT_DATE,但是timestamp或者datetime字段則不需要。
例如,
CREATE?TABLE?t?(d?DATETIME?DEFAULT?CURRENT_TIMESTAMP);
這是合法的。
然后CURRENT_DATE需要用括號(hào)包裹。
CREATE?TABLE?t?(d?DATE?DEFAULT?(CURRENT_DATE));
因?yàn)閐efault子句中指定的默認(rèn)值通常是常量或者表達(dá)式。但是,需要將表達(dá)式默認(rèn)值括在圓括號(hào)內(nèi),以區(qū)別常量默認(rèn)值。
?The default value specified in a DEFAULT clause can be a literal constant or an expression. With one exception, enclose expression default values within parentheses to distinguish them from literal constant default values.
例如:
CREATE?TABLE?t1?(
??--?literal?defaults
??i?INT?????????DEFAULT?0,
??c?VARCHAR(10)?DEFAULT?'',
??--?expression?defaults
??f?FLOAT???????DEFAULT?(RAND()?*?RAND()),
??b?BINARY(16)??DEFAULT?(UUID_TO_BIN(UUID())),
??d?DATE????????DEFAULT?(CURRENT_DATE?+?INTERVAL?1?YEAR),
??p?POINT???????DEFAULT?(Point(0,0)),
??j?JSON????????DEFAULT?(JSON_ARRAY())
);
總結(jié)
mysql中,8.0.13版本之后的允許將Date字段的默認(rèn)值設(shè)置為CURRENT_DATE(當(dāng)前日期),但是之前的版本則不允許。設(shè)置CURRENT_DATE默認(rèn)值,需要將其包裹在圓括號(hào)內(nèi),以區(qū)分常量默認(rèn)值,否則將報(bào)語法錯(cuò)誤。
參考文檔: https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html https://stackoverflow.com/questions/20461030/current-date-curdate-not-working-as-default-date-value/54119983#54119983
?文章來源地址http://www.zghlxwxcb.cn/news/detail-607203.html
點(diǎn)個(gè)“贊 or?在看” 你最好看!
喜歡,就關(guān)注我吧!
文章來源:http://www.zghlxwxcb.cn/news/detail-607203.html
?
到了這里,關(guān)于mysql 將date字段默認(rèn)值設(shè)置為CURRENT_DATE的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!