我有以下查询从表中生成结果的子集。这些结果是~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,)。
我不确定我做错了什么。
答案 0 :(得分:0)
尝试类似下面的内容
update MS
set
MS.EndDate = NULL
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