当与预准备语句一起使用时,我在表上有更新问题。好像mysql正在更新一个错误的列,甚至没有在update命令中指定。
准备:
drop table test1;
create table test1(
id int not null,
show_from timestamp not null,
updated_at timestamp NULL DEFAULT NULL
);
insert into test1(id, show_from, updated_at) values(1, '2018-01-11 12:10:11.19808', '2019-04-15 11:50:00.704748');
在一批中执行此操作:
UPDATE test1 SET show_from='2018-04-15 11:50:00.704748' WHERE id=1;
SELECT * FROM test1;
收益:
1 2018-04-15 13:50:01 2019-04-15 13:50:01
正如所料。
现在一批做到这一点:
PREPARE stmt1 FROM 'UPDATE test1 SET updated_at=? WHERE id=?';
SET @s1='2019-02-11 12:12:11.19808';
SET @s2=1;
EXECUTE stmt1 USING @s1, @s2;
DEALLOCATE PREPARE stmt1;
SELECT * FROM test1;
收益:
1 2019-04-15 12:54:27 2019-02-11 13:12:11
为什么mysql更新了show_from列?
该列声明为timestamp,而不是null:
show_from timestamp not null
在此模式下,MySQL将在每次更新行(其任何列)时更新列。 From the manual:
如果禁用explicit_defaults_for_timestamp
系统变量,则第一个TIMESTAMP
列同时具有DEFAULT CURRENT_TIMESTAMP
和ON UPDATE CURRENT_TIMESTAMP
(如果两者都未明确指定)。
文档提供了解决方法,例如:
- 使用DEFAULT子句定义列,该子句指定常量默认值。
- 指定NULL属性。这也会导致列允许NULL值,这意味着您无法通过将列设置为NULL来分配当前时间戳。
我实际上会推荐这个:
- 启用
explicit_defaults_for_timestamp
系统变量。