首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将创建时间、修改时间列添加到mysql已有表中

将创建时间、修改时间列添加到mysql已有表中
EN

Stack Overflow用户
提问于 2015-12-10 16:52:11
回答 1查看 1.3K关注 0票数 1

我有一张桌子,里面有一些记录。现在,我想向其中添加“已创建”和“已更新”列。我正在使用这样的查询

代码语言:javascript
复制
ALTER TABLE employee ADD COLUMN updated TIMESTAMP NOT NULL DEFAULT 
    CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

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

示例:

代码语言:javascript
复制
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)

默认CURRENT_TIMESTAMP似乎不起作用

EN

回答 1

Stack Overflow用户

发布于 2015-12-10 16:54:57

代码语言:javascript
复制
ALTER TABLE `employee` ADD `COLUMN` 
TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34197351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档