【问题标题】:Duplicate Entry on update of non primary key column更新非主键列时出现重复条目
【发布时间】:2019-06-19 05:37:09
【问题描述】:

我有一个名为 indice_hora 的表,有 6 列:

- 日期 (pk) |合成的 - agent_id (pk) |首要的关键 - 传染病 - 运动 - preenchimento - state_changes

我最近添加了没有默认值的 state_changes 列,所以现在我尝试将所有空值更新为 0。

我正在尝试运行此代码:

update indice_hora
set state_changes = 0
where state_changes is null;

但是我收到了这个错误:

[2019-01-25 08:55:38] [23000][1062] Duplicate entry '2019-01-25 08:55:38-0' for key 'PRIMARY'

为什么即使我没有更新任何键值也会出现此错误?

OBS 1:此表没有任何日期为“2019-01-25 08:55:38-0”的行。
OBS 2:此表主要由触发器更新:

create trigger update_indice_hora_table
  after INSERT
  on indice
  for each row
  INSERT INTO indice_hora VALUES (DATE_FORMAT(NEW.data_hora_registro, '%Y-%m-%d %H:00:00'), NEW.id_agent, NEW.contagem, NEW.mobilidade, NEW.preenchimento, 0)
  ON DUPLICATE KEY UPDATE indice_hora.data            = DATE_FORMAT(NEW.data_hora_registro, '%Y-%m-%d %H:00:00'),
                          indice_hora.id_agent        = NEW.id_agent,
                          indice_hora.contagem        = ((indice_hora.contagem      + NEW.contagem)       / 2),
                          indice_hora.movimento       = ((indice_hora.movimento     + NEW.mobilidade)     / 2),
                          indice_hora.preenchimento   = ((indice_hora.preenchimento + NEW.preenchimento)  / 2);

编辑 1:看起来“2019-01-25 08:55:38-0”是我执行该程序的当前时间。每次我运行脚本时,重复的条目都是当前时间。

【问题讨论】:

  • 您正在再次执行 INSERT,而不是根据触发器在 INSERT 之后更新每一行。你可以看到它。
  • 如果我将“set state_changes = 0”编辑为“set state_changes = 0, date = indice_hora.date”,错误就消失了。为什么?
  • 插入触发器在“indice”表上,但我正在更新“indice_hora”表。这应该不受触发器的影响吧?
  • 是的。确实如此。但是,如果在 indice 和 indice_hora 之间存在任何类型的绑定,例如如果 indice_hora 更新,也更新 indice,那么这将导致同样的问题。还有一件事,尝试执行更新,将所有主键保持在约束中。

标签: mysql sql hibernate spring-boot spring-data-jpa


【解决方案1】:

禁用触发器 -> 运行更新命令 -> 重新启用触发器。

1 禁用触发器

ALTER TRIGGER <TRIGGER_NAME> DISABLE

2 执行您的查询

3 启用触发器

ALTER TRIGGER <TRIGGER_NAME> ENABLE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 2012-08-18
    相关资源
    最近更新 更多