Home > Database > Mysql Tutorial > body text

How to Implement Multiple TIMESTAMP Fields with CURRENT_TIMESTAMP in MySQL?

Mary-Kate Olsen
Release: 2024-11-05 16:45:02
Original
863 people have browsed it

How to Implement Multiple TIMESTAMP Fields with CURRENT_TIMESTAMP in MySQL?

MySQL: Supporting Multiple TIMESTAMP Fields with CURRENT_TIMESTAMP

The MySQL documentation states that a table can only have one TIMESTAMP column with the CURRENT_TIMESTAMP value in either the DEFAULT or ON UPDATE clause. This can be limiting when you want to track both the creation and update timestamps of a record.

Error Handling

When you try to create a table with more than one TIMESTAMP column using CURRENT_TIMESTAMP, you will encounter an error like the following:

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

Solution

Recent versions of MySQL (5.6.25 and later) have addressed this limitation. You can now define tables with multiple TIMESTAMP columns, each with its own CURRENT_TIMESTAMP behavior. Here is an example:

<code class="sql">CREATE TABLE `msgs` (
    `id` INT PRIMARY KEY AUTO_INCREMENT,
    `msg` VARCHAR(256),
    `ts_create` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `ts_update` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);</code>
Copy after login

With this updated syntax, both the ts_create and ts_update columns will be automatically set to the current timestamp when a new record is inserted or an existing record is updated.

The above is the detailed content of How to Implement Multiple TIMESTAMP Fields with CURRENT_TIMESTAMP in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!