我有一个包含userID, sectionId, usersectionID, valid
列的表格。此有效列用于标识重复条目。但是有些重复的条目混合在有效列中。
select userID, sectionId, count(*) as cnt from table where valid = 1 group by 1,2 having cnt >1 ;
这将显示userID和sectionID组合重复条目的列表。如果userid和sectionID组合包含多个条目,则表示存在重复条目。
例如,这可能是输出,
userId SectionID Cnt
1 4 3
现在,当我们进一步看到这一点时,
Select userId, sectionId, usersectionID, valid from table where userID = 1 and sectionID = 4;
userID sectionID usersectionID valid
1 4 3 1
1 4 5 1
1 4 10 1
我想用除了最小usersectionID之外的所有条目更新有效列为0。此查询后的输出应为
userID sectionID usersectionID valid
1 4 3 1
1 4 5 0
1 4 10 0
我想在单个查询中为完整表执行此操作。我已经尝试了很长时间并取得了很大的成功。任何人都可以帮我解决这个问题吗?或者甚至可以在完成这项工作时给出一些想法?
由于
答案 0 :(得分:1)
使用带有自JOIN的UPDATE来查找应标记为无效的重复项。
UPDATE table AS t1
JOIN (SELECT userID, sectionID, MIN(usersectionID) AS minusersectionID
FROM table
WHERE valid = 1
GROUP BY userID, sectionID) AS t2
ON t1.userID = t2.userID AND t1.sectionID = t2.sectionID AND t1.usersectionID != t2.minusersectionID
SET t1.valid = 0
WHERE t1.VALID = 1
答案 1 :(得分:1)
您可以使用以下任何一种方法。
根据最低
更新Update TableName
JOIN (
SELECT userID, sectionID, MIN(userSectionID) AS minuserSectionID
FROM TableName
GROUP BY userID, sectionID
) AS T
Set Valid = 1
WHERE
TableName.userID = T.userID
AND TableName.sectionID = T.sectionID
AND TableName.userSectionID = T.minuserSectionID;
或使用 根据排名第一的值进行更新
SET @rank=0;
Update TableName
JOIN (
SELECT userID, sectionID, @rank:=@rank+1 AS rownumber
FROM TableName
GROUP BY userID, sectionID
) AS T
Set Valid = 1
WHERE
TableName.userID = T.userID
AND TableName.sectionID = T.sectionID
AND T.rownumber = 1;