mysql - 将创建时间,修改时间列添加到mysql中的现有表

标签 mysql database

我有一张包含一些记录的表格。现在我想向其中添加“创建”和“更新”列。我正在使用这样的查询

ALTER TABLE employee ADD COLUMN updated TIMESTAMP NOT NULL DEFAULT 
    CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

但这是创建值全为零的列。我希望它是当前时间戳。

示例:

mysql> select * from employee;  
+----+------+  
| id | name |  
+----+------+  
|  1 | a    |  
|  2 | b    |  
|  3 | c    |  
+----+------+  
3 rows in set (0.00 sec)  

mysql> alter table employee add column updated timestamp not null default current_timestamp on update current_timestamp;  
Query OK, 3 rows affected (0.20 sec)  
Records: 3  Duplicates: 0  Warnings: 0  

mysql> select * from employee;  
+----+------+---------------------+  
| id | name | updated             |  
+----+------+---------------------+  
|  1 | a    | 0000-00-00 00:00:00 |  
|  2 | b    | 0000-00-00 00:00:00 |  
|  3 | c    | 0000-00-00 00:00:00 |  
+----+------+---------------------+  
3 rows in set (0.00 sec)  

mysql> update employee set name='aa' where id='1';  
Query OK, 1 row affected (0.05 sec)  
Rows matched: 1  Changed: 1  Warnings: 0  

mysql> select * from employee;  
+----+------+---------------------+  
| id | name | updated             |  
+----+------+---------------------+  
|  1 | aa   | 2015-12-10 15:41:44 |  
|  2 | b    | 0000-00-00 00:00:00 |  
|  3 | c    | 0000-00-00 00:00:00 |  
+----+------+---------------------+  
3 rows in set (0.00 sec)  

mysql> alter table employee add column city varchar(10) not null default 'banglore';  
Query OK, 3 rows affected (0.17 sec)  
Records: 3  Duplicates: 0  Warnings: 0  

mysql> select * from employee;  
+----+------+---------------------+----------+  
| id | name | updated             | city     |  
+----+------+---------------------+----------+  
|  1 | aa   | 2015-12-10 15:41:44 | banglore |  
|  2 | b    | 0000-00-00 00:00:00 | banglore |  
|  3 | c    | 0000-00-00 00:00:00 | banglore |  
+----+------+---------------------+----------+  
3 rows in set (0.00 sec)

似乎 DEFAULT CURRENT_TIMESTAMP 不起作用

最佳答案

ALTER TABLE `employee` ADD `COLUMN` 
TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP 

关于mysql - 将创建时间,修改时间列添加到mysql中的现有表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34197351/

相关文章:

database - 存储在数据库中的图像在浏览器上显示时被剪切/裁剪

database - 每当 firebase 发生任何变化时,自动向所有用户发送通知

database - PGAdmin 权限被拒绝

java - 使用 JPA 为 Wildfly 构建 Java Web 应用程序失败?

android - 当 MySQL 中行的列变量更改时,如何使应用程序的 View 自动更新

mysql - 如何使用流畅的 api 在 EF6 中映射值对象标识?

java - 如何纠正这个查询?

.net - MySQL 5 的哪个 .NET 数据提供程序?

php - 如何查找同一天同一列的两个日期之间的差异?

database - 可移植数据库列名