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

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

在MySQL中,我们可以通过将该列声明为DEFAULT CURRENT_TIMESTAMP在插入其他列的值时自动向列中插入当前日期和时间。

阅读更多:MySQL 教程

例子

mysql> Create table testing
   -> (
   -> StudentName varchar(20) NOT NULL,
   -> RegDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
   -> );
Query OK,0行受影响(使用时间:0.49秒)

上述查询将创建一个名为“testing”的表,其中一个名为StudentName的列和另一个名为“RegDate”的列声明为DEFAULT CURRENT_TIMESTAMP。现在,在插入值即名称到StudentName列中时,系统会自动将当前日期和时间插入到其他列中。

mysql> Insert into testing(StudentName) values ('Ram');
Query OK,1行受影响(使用时间:0.14秒)

mysql> Insert into testing(StudentName) values ('Shyam');
Query OK,1行受影响(使用时间:0.06秒)

mysql> Select * from testing;
+-------------+---------------------+
| StudentName | RegDate             |
+-------------+---------------------+
| Ram         | 2017-10-28 21:24:24 |
| Shyam       | 2017-10-28 21:24:30 |
+-------------+---------------------+
2行记录(使用时间:0.02秒)

mysql> Insert into testing(StudentName) values ('Mohan');
Query OK,1行受影响(使用时间:0.06秒)

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行记录(使用时间:0.00秒)

通过上述查询,我们可以看到,当将值插入StudentName时,日期和时间也会自动插入。

通过上述概念,我们还可以知道其他列中插入哪个日期和时间。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程