在 MySQL 中向其它列中插入值时如何自动插入当前日期和时间?
在 MySQL 中,可以通过将某列声明为 DEFAULT CURRENT_TIMESTAMP 来实现将当前日期和时间自动插入到某一列,同时在另一列中插入值。
示例
mysql> Create table testing -> ( -> StudentName varchar(20) NOT NULL, -> RegDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP -> ); Query OK, 0 rows affected (0.49 sec)
上述查询将创建一个名为“testing”的表,其中一列名为 StudentName,另一列名为“RegDate”,声明为 DEFAULT CURRENT_TIMESTAMP。现在,在 StudentName 列中插入值,即姓名后,当前日期和时间将自动插入到另一列中。
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)从上述查询中,我们可以看到在 StudentName 中插入值后,日期和时间也自动插入了。
利用上述概念,我们还可以确切地了解另一列中的值的插入日期和时间。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP