DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE字段在INSERT INTO ON DUPLICATE KEY UPDATE没有指定时自动更新失效

【TiDB版本】 5.7.25-TiDB-v5.4.1

建表语句:
CREATE TABLE test_on_update(
id bigint(20) NOT NULL,
user_id bigint(20) DEFAULT NULL,
description VARCHAR(255) DEFAULT NULL,
updated_time TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
PRIMART KEY(id)
);

插入测试数据
INSERT INTO test_on_update (id, user_id,description,updated_time) VALUES (1, 1001, ‘test1’, “2000-01-01 00:00:00”);
INSERT INTO test_on_update (id, user_id,description,updated_time) VALUES (2, 1002, ‘test2’, “2000-01-01 00:00:00”);
INSERT INTO test_on_update (id, user_id,description,updated_time) VALUES (3, 1003, ‘test3’, “2000-01-01 00:00:00”);

执行以下语句的时候, updated_time会自动更新为当前时间
UPDATE test_on_update SET description=‘test_description_update’ WHERE id=1;

【问题】 为什么执行以下语句的时候,updated_time不会自动更新
INSERT INTO test_on_update (id) VALUES (2) ON DUPLICATE KEY UPDATE str = “test_description_insert”;

为什么需要如下指定,updated_time才会更新
INSERT INTO test_on_update (id) VALUES (2) ON DUPLICATE KEY UPDATE str = “test_description_insert”,updated_time=NOW();

您好,我使用这个SQL:

CREATE TABLE test_on_update(
	id bigint(20) NOT NULL,
	user_id bigint(20) DEFAULT NULL,
	description VARCHAR(255) DEFAULT NULL,
	updated_time TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
	PRIMARY KEY(id)
);

INSERT INTO test_on_update (id, user_id,description,updated_time) VALUES (1, 1001, 'test1', "2000-01-01 00:00:00");
INSERT INTO test_on_update (id, user_id,description,updated_time) VALUES (2, 1002, 'test2', "2000-01-01 00:00:00");
INSERT INTO test_on_update (id, user_id,description,updated_time) VALUES (3, 1003, 'test3', "2000-01-01 00:00:00");

INSERT INTO test_on_update (id) VALUES (2) ON DUPLICATE KEY UPDATE description = "test_description_insert";

updated_time 字段是可以更新的:

SELECT * FROM test_on_update;
+----+---------+-------------------------+----------------------------+
| id | user_id | description             | updated_time               |
+----+---------+-------------------------+----------------------------+
| 1  | 1001    | test1                   | 2000-01-01 00:00:00        |
| 2  | 1002    | test_description_insert | 2022-06-29 12:01:38.789075 |
| 3  | 1003    | test3                   | 2000-01-01 00:00:00        |
+----+---------+-------------------------+----------------------------+

你好~ 你用的也是 5.7.25-TiDB-v5.4.1 这个版本么

我用的 v6.1.0,等下换成你的版本试一下。

你好,我这边验证也是可以的,版本是5.3.0

我好像知道为什么了,如果执行的是 INSERT INTO test_on_update (id) VALUES (2) ON DUPLICATE KEY UPDATE description = “test2”; 那updated_time就不会自动更新了, 因为需要更新的字段的内容与原来一致的话,那TiDB没有做实际的更新操作,最后test_on_update字段自然也就不会更新了,所以TiDB在做update操作之前,是还会做一次校验吗

是的,我这边也发现了。这种情况应该不算update吧。

是的,没执行实际的update操作确实不算update

是的,这种情况不算做Update。可以从affected_rows看出。

此话题已在最后回复的 1 分钟后被自动关闭。不再允许新回复。