Home >Database >Mysql Tutorial >How to automatically insert current date and time when inserting values ​​in other columns in MySQL?

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

王林
王林forward
2023-09-13 22:29:101551browse

如何在 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)

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)

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete