I have seen a lot of related questions, but I cannot place my finger on this specific question:
I have a MySQL table with both a TIMESTAMP (for when the field was created) and a DATETIME (for each time the field gets updated). It looks like this:
CREATE TABLE 'vis' (
ID BIGINT PRIMARY KEY AUTO_INCREMENT NOT NULL,
ENTRY VARCHAR(255),
AUTHOR VARCHAR(255),
CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UPDATED_AT DATETIME ON UPDATE CURRENT_TIMESTAMP,
UPDATED_BY VARCHAR(255)
)
When I try this though, the error I am getting is: (SQL Error: 1294 SQL State: HY000) - Invalid ON UPDATE clause for 'updated_at' field
Everywhere I have read (even on Stack Overflow) suggests I should be able to do this, yet I am getting this error. Perhaps there is another way to have a field that automatically updates the time each time I update it?
I am using MySQL Server 5.5.
To update with the current date and time: UPDATE table_name SET date_field = CURRENT_TIMESTAMP; To update with a specific date value: UPDATE table_name SET date_field = 'YYYY-MM-DD HH:MM:SS.
With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP , the column has the current timestamp for its default value and is automatically updated to the current timestamp.
Here is the SQL you can use to add the column in: ALTER TABLE `table1` ADD `lastUpdated` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ; This adds a column called 'lastUpdated' with a default value of the current date/time.
DATETIME
cannot use CURRENT_TIMESTAMP
on update. Instead, change it to a TIMESTAMP
.
Or, consider using a trigger for this situation: http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html
EDIT: As in the comments (thanks @АлександрФишер!), this is no longer the case since MySQL 5.6.5, so another solution is to upgrade your server if possible.
That feature appears to have been introduced in 5.6. Works as expected on my default OS X install.
Reference: Automatic Timestamp Properties Before MySQL 5.6.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With