mysql插入修改数据时自动添加当前时间戳

更多请看(www.omob.cc)

代码格式:

CREATE TABLE table_name
(
    timestamp_name TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

示例:

mysql> desc test;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| username | varchar(16) | YES  | UNI | NULL    |                |
| version  | int(3)      | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> alter table test drop column version;
Query OK, 0 rows affected (0.20 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table test add column time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
Query OK, 0 rows affected (0.25 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc test;
+----------+-------------+------+-----+-------------------+-----------------------------+
| Field    | Type        | Null | Key | Default           | Extra                       |
+----------+-------------+------+-----+-------------------+-----------------------------+
| id       | int(11)     | NO   | PRI | NULL              | auto_increment              |
| username | varchar(16) | YES  | UNI | NULL              |                             |
| time     | timestamp   | YES  |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+----------+-------------+------+-----+-------------------+-----------------------------+
3 rows in set (0.00 sec)

mysql> insert into test(username) values('mary');
Query OK, 1 row affected (0.08 sec)

mysql> select * from test;
+----+-----------+---------------------+
| id | username  | time                |
+----+-----------+---------------------+
|  1 | zhangsan4 | 2018-07-10 20:19:13 |
|  2 | mary      | 2018-07-10 20:21:14 |
+----+-----------+---------------------+
2 rows in set (0.00 sec)


mysql> update test set username='lisa' where id=2;
Query OK, 1 row affected (0.10 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from test;
+----+-----------+---------------------+
| id | username  | time                |
+----+-----------+---------------------+
|  1 | zhangsan4 | 2018-07-10 20:19:13 |
|  2 | lisa      | 2018-07-10 20:22:42 |
+----+-----------+---------------------+
2 rows in set (0.00 sec)

猜你喜欢

转载自blog.csdn.net/thinktik/article/details/80991629