我有一个表test
有4列
id name visited updated_at
1 abc 2016-03-20 2016-03-20
2 xyz 2016-03-23 2016-03-23
当我申请以下查询时
ALTER TABLE `test` CHANGE `updated_at` `updated_at` TIMESTAMP on update
CURRENT_TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00';
如果我更改name
或visited
,
但我希望它仅在visited
更改时才会更改。
如何实现这一目标?谢谢你的帮助。
答案 0 :(得分:2)
听起来你需要一个触发来完成它。假设您的表定义如下:
ContentView.BindingContext
...您可以通过触发器实现仅针对ContentPage.BindingContext
列更新drop table if exists test;
create table test(
id BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL DEFAULT '',
visited DATETIME NOT NULL DEFAULT '0000-00-00',
updated_at DATETIME NOT NULL DEFAULT '0000-00-00'
);
的目标,如此。
updated_at
你可以看到它与一个相当直接的例子一起工作。
visited
答案 1 :(得分:1)
drop table if exists `xyz1`;
create table `xyz1`
( id int auto_increment primary key,
theName varchar(20) not null,
visited timestamp null,
updated_at timestamp null
);
insert `xyz1` (theName) values('abc'),('xyz');
对我们当前的NULL坐在那里感到不满,错误1138:
ALTER TABLE `xyz1` CHANGE `updated_at` `updated_at` TIMESTAMP
NOT NULL DEFAULT CURRENT_TIMESTAMP;
让我们解决一下:
truncate table `xyz1`;
ALTER TABLE `xyz1` CHANGE `updated_at` `updated_at` TIMESTAMP
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
-- works
insert `xyz1` (theName) values('abc'),('xyz');
select * from `xyz1`;
+----+---------+---------+---------------------+
| id | theName | visited | updated_at |
+----+---------+---------+---------------------+
| 1 | abc | NULL | 2016-06-16 14:39:38 |
| 2 | xyz | NULL | 2016-06-16 14:39:38 |
+----+---------+---------+---------------------+
update `xyz1` set `theName`='xyz Smith' where id=2;
select * from `xyz1`;
+----+-----------+---------+---------------------+
| id | theName | visited | updated_at |
+----+-----------+---------+---------------------+
| 1 | abc | NULL | 2016-06-16 14:39:38 |
| 2 | xyz Smith | NULL | 2016-06-16 14:41:04 |
+----+-----------+---------+---------------------+