MySQL auto-store datetime for each row

江枫思渺然 提交于 2019-11-26 19:06:04

问题


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?


回答1:


You can use DEFAULT constraints to set the timestamp:

ALTER TABLE
 MODIFY dt_created datetime DEFAULT CURRENT_TIMESTAMP

ALTER TABLE
 MODIFY dt_modified datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Then you wouldn't have to specify NOW() in your INSERT/UPDATE statements.

Reference: TIMESTAMP properties




回答2:


If you're using phpmyadmin you can do this by :




回答3:


ALTER TABLE  `tablename` CHANGE  `dt`  `dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

should be the correct code.




回答4:


Well, you can't have both:

mysql doc:

It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.

Sad, isn't it?

You could however use null instead of now() following this tip




回答5:


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.




回答6:


In phpmyadmin you can set

OR use this query

ALTER TABLE  `tablename`
    CHANGE  `dt_created`  `dt_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP



回答7:


could be set as default an on update of rows

ALTER TABLE `tablename` CHANGE `dt` `dt` TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;


来源:https://stackoverflow.com/questions/1932093/mysql-auto-store-datetime-for-each-row

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