Update mysql table with same values and still get a timestamp update

冷暖自知 提交于 2020-01-03 13:01:33

问题


So I have this stamp timestamp DEFAULT NOW() ON UPDATE NOW() row on my table, and I need it to update even when the update I'm executing is basically same data on all fields.

Is there any way of doing this within the declaration of the table, like some other option other than on update, or do I have to force a stamp = now() every time I update (and remove the on update of course since it will be useless).

I've seen this thread, but it only answers what is happening and why, not how to get around it other than forcing it indirectly


回答1:


You'd have to use a trigger to force it each time.

DELIMITER GO

CREATE TRIGGER `mydb`.`mytable_U` BEFORE UPDATE ON `mydb`.`mytable`  
FOR EACH ROW 
BEGIN  
    SET NEW.stamp = CURRENT_TIMESTAMP;   
END
GO

DELIMITER ;



回答2:


As @veeTrain said, it'd be easy if you added it to your update statement. This is just another way of doing it, you can also use unix_timestamp().

UPDATEtable_nameSETlast_logged_in= unix_timestamp() WHEREid= '$user_id'

I know my response is late, but I ran into a similar issue and figured I'd share my solution for those encountering this thread in the future.




回答3:


I find it easier to just do the following as part of your update statement:

UPDATE table_name SET last_logged_in = NOW() WHERE `user_id`...

This way the value is always updated and if nothing else has changed the timestamp still gets updated. Thanks for your question; it was the same as mine.



来源:https://stackoverflow.com/questions/8657189/update-mysql-table-with-same-values-and-still-get-a-timestamp-update

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