问题
I am creating some tables where I want to store the time when a record was created and when it was last updated. I thought I could have two timestamp fields where one would have the value CURRENT_TIMESTAMP
and the other would have CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
. But I guess I can't do this because you can have only 1 timestamp field with a default value in a table?
How would you recommend I get and store the two times? Thanks!
回答1:
You can have two columns of type timestamp in one table.
The following works for MySQL 5.0
create table t ( id integer, created_at timestamp default current_timestamp, updated_at timestamp );
I think you are confusing this with SQL Server (where timestamp is not really a "time stamp" and there is indeed a limit on a single "timestamp" column)
Edit: But you will need a trigger to update the update_at column each time the row is changed.
回答2:
A good way to create fields like 'created' and 'updated' is
CREATE TABLE `mytable` (
`id` INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
`created` TIMESTAMP DEFAULT '0000-00-00 00:00:00',
`updated` TIMESTAMP DEFAULT now() ON UPDATE now(),
`myfield` VARCHAR(255)
);
And its necessary to enter nulls into both columns during "insert":
INSERT INTO mytable (created,updated,myfield) VALUES (null,null,'blablabla');
And now, in all updates, the 'updated' field will have a new value with actual date.
UPDATE mytable SET myfield='blablablablu' WHERE myfield='blablabla';
Source : http://gusiev.com/2009/04/update-and-create-timestamps-with-mysql/
回答3:
As of MYSQL version 5.6.5 you can do this using DEFAULT and ON UPDATE. No triggers are needed.
ts_create
TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
ts_update
TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
回答4:
As far as I know, there's no workaround for that restriction. You'll need to manually set (at least) one of the timestamps, the easiest way is just add updated = NOW()
to the UPDATE
-query.
回答5:
You'll need two columns: CREATE_TIME and UPDATE_TIME.
You might want to add CREATE_USER and UPDATE_USER.
Perhaps you'd want to have a 1:many relationship with name of column changed, old and new values.
It's all part of change data capture. You could have CDC tables that are updated using triggers.
回答6:
I would leave the current timestamp the way you suggested and fill in the created_at field with current date on insert.
来源:https://stackoverflow.com/questions/3488536/mysql-create-time-and-update-time-timestamp