Update timestamp column in Application or Database?

妖精的绣舞 提交于 2019-12-24 00:36:25

问题


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

回答1:


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.




回答2:


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.




回答3:


is it good practice to have date_created and date_modified on every table?

Sure.
I'd throw in date_deleted also.

Update timestamp column in Application or Database?

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?



来源:https://stackoverflow.com/questions/7291104/update-timestamp-column-in-application-or-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!