在MySQL中实现DEFAULT CURRENT_TIMESTAMP和ON UPDATE CURRENT_TIMESTAMP

使用DEFAULT CURRENT_TIMESTAMP和ON UPDATE CURRENT_TIMESTAMP时,列具有默认值的当前时间戳,并自动更新为当前时间戳。

让我们看一个例子并创建一个表-

mysql> create table DemoTable737 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(100),
   StudentAdmissiondate datetime
);

以下是对MySQL中的CURRENT_TIMESTAMP和ON UPDATE CURRENT_TIMESTAMP的查询-

mysql> alter table DemoTable737 modify column StudentAdmissiondate 
timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
Records: 0 Duplicates: 0 Warnings: 0

让我们再次检查表的描述-

mysql> desc DemoTable737;

这将产生以下输出-

+----------------------+--------------+------+-----+-------------------+-----------------------------+
| Field                | Type         | Null | Key | Default           | Extra                       |
+----------------------+--------------+------+-----+-------------------+-----------------------------+
| StudentId            | int(11)      | NO   | PRI | NULL              | auto_increment              |
| StudentName          | varchar(100) | YES  |     | NULL              |                             |
| StudentAdmissiondate | timestamp    | YES  |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+----------------------+--------------+------+-----+-------------------+-----------------------------+
3 rows in set (0.01 sec)