更新应用程序或数据库中的时间戳列?
我在数据库中的每个表上都有 date_created 和 date_modified 列。
使用 MySQL 触发器在数据库中设置时间戳列与使用 PHP 在应用程序层设置时间戳列相比有何优点/缺点?
当部署在许多服务器上时,哪个更容易维护并且具有更好的时间同步性?
编辑: 既然 Johan 建议在数据库中设置时间戳很好,那么这些实现是否正确? 另外,在每个表上都有 date_created 和 date_modified 是个好习惯吗? 或者您建议将它们添加到某些表上?
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
date_modified TIMESTAMP NOT NULL DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP
I have date_created and date_modified columns on each table in database.
What are advantages/disadvantages setting timestamp columns at database using MySQL triggers vs setting them at application layer using PHP?
Which is easier to maintain and have better time synchronization when deployed across on many servers?
EDIT:
since Johan suggested setting timestamps in database is good, are these correct implementations?
additionally, is it good practice to have date_created and date_modified on every table?
or do you recommend adding them on certain tables?
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
date_modified TIMESTAMP NOT NULL DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
数据库中的时间戳。
如果您在主从设置中进行复制,则会正确复制数据库时间戳(使用原始时间戳)。
您不会(!)在触发器中设置时间戳。
相反,您在表定义中指定它们,MySQL 将在插入和/或更新时自动设置正确的时间戳。
您只需在创建(或更改)表时设置它们一次即可。
再简单不过了。
Timestamp in the database.
If you replicate in a master-slave setup, database timestamps are correctly replicated (using the original timestamp).
You do not (!) set timestamps in triggers.
Instead you specify them in the table definition, MySQL will automatically set the correct timestamp on insert and/or update.
You only have to set them once, when you create (or alter) the table and that's it.
Could not be easier.
您可以自行决定哪些表应该具有时间戳列。在我们的生产环境中,每个表都有这些列。
但是,我们也在代码中设置了这些值。我相信这样做是为了让日期完全控制应用程序。要知道,无论采用哪种方式,复制都会很好。如果您确实在应用程序中设置了日期,并且需要数据库服务器时间而不是应用程序服务器时间,只需使用 MySQL 的 NOW() 函数设置列即可。
It's your discretion regarding which tables should have timestamp columns. In our production environment, every table has these columns.
However, we also set the values in code. I believe that this was done so that the dates were in full control of the application. Know that either way you do it, replication will be fine. If you do set the dates in the application and you want DB server time instead of application server time, simply set the columns using MySQL's NOW() function.
当然。
我也会加入 date_deleted 。
取决于您计划如何使用这些字段。
如果是某篇文章,并且您想显示上次编辑时间,则永远不应该使用 mysql 时间戳功能,因为它最终会产生意外结果,例如数据库中所有记录的更新时间相同。
触发器也一样。
不要偷懒,手动设置该字段。它不会花费你任何成本,因为你已经使用 ORM 来做到这一点,不是吗?
Sure.
I'd throw in date_deleted also.
Depends on how you plan to use these fields.
If it's some article and you want to show last editing time, you should never use mysql timestamp features as it will end up with unexpected results, like same update time in all records in database.
Same for the trigger.
don't be lazy, set this field manually. It will cost you nothing as you already using ORM to do it, don't you?