我有以下查询,它从表中生成结果的子集。这些结果约为 3000,状态表中有 ~230,000 个 roes:
SELECT ms1.* FROM STATUS MS1
INNER JOIN
(
SELECT MS.EndDate as MDT, MS.ID, MS.StatusID, MS.StartDate
FROM MEMBER M
INNER JOIN STATUS MS ON MS.ID = M.ID
AND MS.StartDate =(SELECT MAX(StartDate) FROM STATUS WHERE STATUS.ID = M.ID)
WHERE MS.EndDate IS NOT NULL
GROUP BY MS.ID, MS.StatusID, MS.EndDate, MS.StartDate ) MS2
ON MS1.ID = ms2.ID AND MS1.StatusID = MS2.StatusID
我要更新的正是这些从查询返回的记录。然后我接受上面的查询并将其包装在更新语句中,如下所示:
UPDATE STATUS
SET EndDate = NULL
WHERE EXISTS
(
INNER JOIN
(
SELECT MS.EndDate as MDT, MS.ID, MS.StatusID, MS.StartDate
FROM MEMBER M
INNER JOIN STATUS MS ON MS.ID = M.ID
AND MS.StartDate =(SELECT MAX(StartDate) FROM STATUS WHERE STATUS.ID = M.ID)
WHERE MS.EndDate IS NOT NULL
GROUP BY MS.ID, MS.StatusID, MS.EndDate, MS.StartDate ) MS2
ON MS1.ID = ms2.ID AND MS1.StatusID = MS2.StatusID
)
我违反了一条不在上面原始选择中的记录的唯一键约束,因此更新正在尝试更新我不希望它更新的行。我得到的信息是:
违反 UNIQUE KEY 约束“UK_status_ID_ENDDATE”。无法在对象“dbo.STATUS”中插入重复键。重复键值为 (3, )。
我不确定我做错了什么。