一条sql对mysql数据库中重复记录去重

前几天接到一个数据库去重的需求,大概意思是这样的:我们数据库中有一个存储用户第三方信息的表,因为之前程序漏洞导致记录中一个用户对应了多个第三方信息。现在需要保证一个用户ID只能有一条记录,对于多条记录的用户ID保留最近绑定的记录。

数据库表结构

user_thirdpart` (

USER_ID int(11) NOT NULL COMMENT,

THIRD_MESSAGE text CHARACTER,

GMT_CREATE timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

解决方法

百度了各种方法之后还是后未能成功,最终结合网上的方法解决。具体sql如下

DELETE user_thirdpart 
FROM  user_thirdpart, 
 (
        SELECT
            user_id,
            max(gmt_create) gmt_create
        FROM
            user_thirdpart
        GROUP BY
            user_id
        HAVING
            count(1) > 1
    ) temp
WHERE
    user_thirdpart.user_id = temp.user_id 
    AND user_thirdpart.gmt_create < temp.gmt_create

sql解析:

  • ( SELECT user_id, max(gmt_create) gmt_create FROM user_thirdpart GROUP BY user_id HAVING count(1) > 1) temp 从表中查询出多次出现的user_id记录,并返回创建时间最大的一条记录作为临时表 temp
  • where user_thirdpart.user_id = temp.user_id AND user_thirdpart.gmt_create < temp.gmt_create关联判断重复条件的字段
  • 删除user_thirdpart中 where条件满足的记录

你可能感兴趣的:(一条sql对mysql数据库中重复记录去重)