I have the following table schema;
CREATE TABLE `db1`.`sms_queue` (
`Id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`Message` VARCHAR(160) NOT NULL DEFAULT 'Unknown Message Error',
`CurrentState` VARCHAR(10) NOT NULL DEFAULT 'None',
`Phone` VARCHAR(14) DEFAULT NULL,
`Created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`LastUpdated` TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP,
`TriesLeft` tinyint NOT NULL DEFAULT 3,
PRIMARY KEY (`Id`)
)
ENGINE = InnoDB;
It fails with the following error:
ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause.
My question is, can I have both of those fields? or do I have to manually set a LastUpdated field during each transaction?
There is a trick to have both timestamps, but with a little limitation.
You can use only one of the definitions in one table. Create both timestamp columns like so:
Note that it is necessary to enter
null
into both columns duringinsert
:i think this is the better query for stamp_created and stamp_updated
because when the record created,
stamp_created
should be filled bynow()
andstamp_updated
should be filled by'0000-00-00 00:00:00'
For mysql 5.7.21 I use the following and works fine:
CREATE TABLE
Posts
(modified_at
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,created_at
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP )From the MySQL 5.5 documentation:
Changes in MySQL 5.6.5:
You can have them both, just take off the "CURRENT_TIMESTAMP" flag on the created field. Whenever you create a new record in the table, just use "NOW()" for a value.
Or.
On the contrary, remove the 'ON UPDATE CURRENT_TIMESTAMP' flag and send the NOW() for that field. That way actually makes more sense.
If you do decide to have MySQL handle the update of timestamps, you can set up a trigger to update the field on insert.
MySQL Reference: http://dev.mysql.com/doc/refman/5.0/en/triggers.html