How to automatically insert current date and time when inserting values in other columns in MySQL?

王林
Release: 2023-09-13 22:29:10
forward
1314 people have browsed it

如何在 MySQL 的其他列中插入值时自动插入当前日期和时间?

In MySQL, by declaring the column as DEFAULT CURRENT_TIMESTAMP, we can automatically insert the current date and time into the column when inserting a value into another column.

Example

mysql> Create table testing -> ( -> StudentName varchar(20) NOT NULL, -> RegDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP -> ); Query OK, 0 rows affected (0.49 sec)
Copy after login

The above query will create a table "testing" with a column named StudentName and an additional column named "RegDate" declared as DEFAULT CURRENT_TIMESTAMP. Now, when inserting a value (i.e. name) in the StudentName column, the current date and time will be automatically inserted into another column.

mysql> Insert into testing(StudentName) values ('Ram'); Query OK, 1 row affected (0.14 sec) mysql> Insert into testing(StudentName) values ('Shyam'); Query OK, 1 row affected (0.06 sec) mysql> Select * from testing; +-------------+---------------------+ | StudentName | RegDate | +-------------+---------------------+ | Ram | 2017-10-28 21:24:24 | | Shyam | 2017-10-28 21:24:30 | +-------------+---------------------+ 2 rows in set (0.02 sec) mysql> Insert into testing(StudentName) values ('Mohan'); Query OK, 1 row affected (0.06 sec) mysql> Select * from testing; +-------------+---------------------+ | StudentName | RegDate | +-------------+---------------------+ | Ram | 2017-10-28 21:24:24 | | Shyam | 2017-10-28 21:24:30 | | Mohan | 2017-10-28 21:24:47 | +-------------+---------------------+ 3 rows in set (0.00 sec)
Copy after login

From the above query, we can see that when inserting a value into StudentName, the date and time are also automatically inserted.

With the help of the above concept, we can also know exactly the date and time when the values in other columns were inserted.

The above is the detailed content of How to automatically insert current date and time when inserting values in other columns in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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 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!