Timestamp for row creation and last modification

血红的双手。 提交于 2019-12-10 12:57:09

问题


I need to keep track of the time a row was inserted into the database, and the time it was last modified.

I tried to create two separate columns, and use CURRENT_TIMESTAMP:

create table def (
  id int, 
  creation timestamp 
    default CURRENT_TIMESTAMP, 
  modification timestamp 
    on update CURRENT_TIMESTAMP
);

However, this produced an error:

ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause

What is the best way to do this?

I'm thinking stored procedure, but looking for a standard solution. I'm also concerned with access privileges -- as few programs/things should be able to touch the timestamps as possible.


Although I would prefer MySQL answers, solutions for other RDBMS's are also appreciated!


回答1:


Ya this is a lame limitation on MySQL. If you are going through an application you can add a time() call for the created_at column, and let the updated_at column use the CURRENT_TIMESTAMP.

$sql = "INSERT INTO my_table SET name = 'Mike', created_at = " . time();

I'd opt to do this on the created_at column as it probably won't be touched as often as the updated_at column.

-- Edit --

Better yet, use MySQL's built in now() function. This way you only need to be concerned with the timezone of the mysql server, and not the timezones of the app server AND the mysql server.

$sql = "INSERT INTO my_table SET name = 'Mike', created_at = NOW()";



回答2:


You can use a trigger. The application can also set the value, but if do, it will be overwritten by the database.

delimiter //
CREATE TRIGGER def_bef_update BEFORE UPDATE ON def FOR EACH ROW BEGIN
    SET NEW.modification = CURRENT_TIMESTAMP;
END//
delimiter ;

You can also use it to check the data and update your modification date only if has important changes.



来源:https://stackoverflow.com/questions/8364430/timestamp-for-row-creation-and-last-modification

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