mysql - 查找重复条目并更新列 - Mysql

标签 mysql sql

我有一个包含 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 组合有超过 1 个条目,则意味着存在重复条目。

例如,这可能是输出,

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

我想在单个查询中对整个表执行此操作。我已经尝试了很长时间并且取得了很大的成功。有人能帮我解决这个问题吗?或者甚至可以提供一些完成这项工作的想法?

谢谢

最佳答案

使用带有自连接的更新来查找应标记为无效的重复项。

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

关于mysql - 查找重复条目并更新列 - Mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36293825/

相关文章:

sql - 几乎相同值的日期比较

SQL 连接 3 个表,具有多个 WHERE 子句匹配

mysql - 按日期获取最后记录,但对于 2 个不同的 ID

php - PDO - 对多个 foreach 循环使用相同的查询

MYSQL统计不为空的行

c# - 解析SQL查询并提取列名和表名

mysql - 统计用户 session 数

mysql - SQL 设计模式 : how do I store multiple unique ids from different sites in mashup?

mysql - 将具有相同ID但不同列值的两行合并为一行[mysql]

mysql - MySQL 中的分组选择