MySQL:添加当前年份作为字段“年份”的默认值
我在 MySQL(版本 5)中有下表:
id int(10) UNSIGNED No auto_increment
year varchar(4) latin1_swedish_ci No
title varchar(250) latin1_swedish_ci Yes NULL
body text latin1_swedish_ci Yes NULL
我希望数据库在插入时自动添加当前年份,我尝试了以下 SQL 语句:
ALTER TABLE `tips` CHANGE `year` `year` VARCHAR(4) NOT NULL DEFAULT year(now())
但它给出了以下错误:
1067 - Invalid default value for 'year'
我该怎么做才能获得此功能? 提前致谢!
I have the following table in MySQL (version 5):
id int(10) UNSIGNED No auto_increment
year varchar(4) latin1_swedish_ci No
title varchar(250) latin1_swedish_ci Yes NULL
body text latin1_swedish_ci Yes NULL
And I want the db to auto add the current year on insert, I've tried the following SQL statement:
ALTER TABLE `tips` CHANGE `year` `year` VARCHAR(4) NOT NULL DEFAULT year(now())
But it gives the following error:
1067 - Invalid default value for 'year'
What can I do to get this functionality? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
-- MySQL 手册
但是,您可以,编写一个设置该值的触发器。 我希望我能提供帮助,但我不太熟悉在 MySQL 中编写存储过程。
我认为这会起作用:
-- MySQL Manual
You can, however, write a trigger that sets the value. I wish I could help, but I'm not really familiar with writing stored procedures in MySQL.
I think this would work:
以下内容应该有效:
请参阅年份数据类型了解更多信息。
因此,我在获得访问权限后对其进行了测试,但它不起作用。 正如另一张海报指出的那样 CURRENT_TIMESTAMP 仅适用于 TIMESTAMP 数据类型。
存储完整的时间戳然后仅在代码中使用年份是否存在特定问题? 如果没有,那么我建议将此值存储为时间戳。
您的另一个选择是创建一个触发器:
否则,将此值分配给代码中的 INSERT 语句。
您的情况的最佳解决方案将完全取决于您的特定应用程序的环境。
The following should work:
Please see Year Data Type for further information.
So, I tested this once I got access and it doesn't work. As another poster pointed out CURRENT_TIMESTAMP only works on the TIMESTAMP data type.
Is there a specific problem with storing a complete time stamp and then only using the year in your code? If not, then I would recommend storing this value as a timestamp.
Your other option would be to create a trigger:
Otherwise, assign this value to the INSERT statement from within your code.
The best solution in your case will depend entirely on the circumstances surrounding your particular application.
我知道这是一篇相当老的帖子,但对于其他人来说仍然通过搜索引擎找到它。 从 MySQL 8.0.13 开始,您可以使用 表达式作为列默认值。 所以,你原来的 alter 语句是有效的。 您只需将其括在括号中即可,如下所示。 我还建议使用
YEAR
数据类型 代替了 varchar,它包含验证和内置转换; 例如10
将转换为2010
等...I know this is a fairly old post, but for others still finding this via search engines. As of MySQL 8.0.13, you can use expressions as column defaults. So, your original alter statement is valid. You just need to wrap it in parentheses like so. I would also suggest to use the
YEAR
data type instead of varchar, it contains validation and built-in conversions; like10
will be converted to2010
etc...