MySQL自动存储每行的日期时间
在 MySQL 中,我厌倦了将列 dt_created
和 dt_modified
(分别是创建和最后修改的日期时间戳)添加到数据库中的所有表中。
每次INSERT
或UPDATE
数据库时,我都必须使用NOW()
关键字。这一切都贯穿了我的坚持。
是否有任何有效的替代方案,MySQL 可以自动存储至少插入行的数据时间并让我检索它?
In MySQL, I'm sick of adding the columns dt_created
and dt_modified
(which are date time stamps for creation and last modified respectively) to all the tables I have in my database.
Every time I INSERT
or UPDATE
the database, I will have to use the NOW()
keyword. This is going all over my persistence.
Is there any efficient alternative where MySQL can automatically store at least the datatime of the row that is inserted and let me retrieve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用 DEFAULT 约束来设置时间戳:
这样您就不必在 INSERT/UPDATE 语句中指定
NOW()
。参考: TIMESTAMP 属性
You can use DEFAULT constraints to set the timestamp:
Then you wouldn't have to specify
NOW()
in your INSERT/UPDATE statements.Reference: TIMESTAMP properties
如果您使用 phpmyadmin,您可以通过以下方式执行此操作:
If you're using phpmyadmin you can do this by :
应该是正确的代码。
should be the correct code.
好吧,你不能两者兼得:
mysql doc:
很难过,不是吗?
但是,您可以使用 null 代替 now() 按照此提示< /a>
Well, you can't have both:
mysql doc:
Sad, isn't it?
You could however use null instead of now() following this tip
这里提出了类似的问题“Timestamp for MySQL”时间戳字段将在每次访问时更新。您还可以考虑在相关表上放置一个 触发器自动为您填充这些字段。根据环境的不同,有些商店/企业不喜欢使用触发器,因此您可能必须找到替代的解决方法。
Similar question was asked here "Timestamp for MySQL" the timestamp field will update every time it is accessed. You might also consider a Trigger placed on the table in question to automatically populate those fields for you. Depending on the environment some shops/businesses do not like the use of triggers and so you might have to find alternate work arounds.
在 phpmyadmin 中你可以设置
或
使用此查询
In phpmyadmin you can set
OR
use this query
可以设置为默认行更新
could be set as default an on update of rows