【发布时间】:2021-05-25 12:08:56
【问题描述】:
问题说明
我不会更新 3 个主键连接的最后一个主键。但问题有时是多个记录的第一个和第二个主键相同。在这种情况下,当我设置我的新值时,即使我使用子请求来避免这个问题,我也会有一个重复的条目键。
一些代码
架构
create table llx_element_contact
(
rowid int auto_increment
primary key,
datecreate datetime null,
statut smallint default 5 null,
element_id int not null,
fk_c_type_contact int not null,
fk_socpeople int not null,
constraint idx_element_contact_idx1
unique (element_id, fk_c_type_contact, fk_socpeople)
)
更新请求
此请求返回重复键错误
update llx_element_contact lec
set lec.fk_socpeople = 64
where
-- Try to avoid the error by non including the values that are the same
(select count(*)
from llx_element_contact ec
where ec.fk_socpeople = 64
and ec.element_id = lec.element_id
and ec.fk_c_type_contact = lec.fk_c_type_contact) = 0
测试数据
rowid, datecreate, statut, element_id, fk_c_type_contact, fk_sockpeople
65,2015-08-31 18:59:18,4,65,160,30
66,2015-08-31 18:59:18,4,66,159,12
67,2015-08-31 18:59:18,4,67,160,12
15283,2016-03-23 11:47:15,4,6404,160,39
15284,2016-03-23 11:51:30,4,6404,160,58
【问题讨论】:
-
“dup 错误”问题是数据示例中的最后 2 行。更新后两者都会有
(element_id, fk_c_type_contact, fk_socpeople) = (6404,160,64),但这个组合被定义为唯一。您是唯一可以说出在这种情况下必须执行的操作的人。其中一行(究竟是什么?)必须保持不变?别的东西?这不是SQL代码的问题,是缺少算法的问题。而且必须从代码中解决。 -
根据查询过滤表中相同字段 = 64 的元素将字段更新为 64 是否有意义?
-
@Akina 我想根据最近的日期更改第一个
-
@JaimeDrq 我没有包含我的过滤器,因为这不是这个问题的目的,但当然在我的实际数据库中我有一些条件可以做到这一点:)