zoukankan      html  css  js  c++  java
  • MySQL中分组取第一条, 以及删除多余的重复记录

    检查重复记录

    -- 检查重复code1
    select count(identity) num, identity from event_log 
    where code='code1' 
    group by identity having count(identity) > 1
    order by num desc

    删除重复记录

    DELETE FROM event_log WHERE `code`='code1' AND identity IN (
        SELECT identity from (
            SELECT identity FROM event_log WHERE code='code1' GROUP BY identity HAVING count(identity) > 1
        ) a
    ) AND id NOT IN (
        SELECT keepId FROM (
            SELECT min(id) keepId FROM event_log WHERE code='code1' GROUP BY identity HAVING count(identity) > 1
        ) b
    )

    其中 a 和 b 两个中间表的作用是, 避免执行时出现  You can't specify target table 'xxxxx' for update in FROM clause 错误

    分组按时间正序取第一条记录, 巧妙地使用了not exists

    select d.* from t_charge d where not exists (select 1 from t_charge where user_id = d.user_id and created_at < d.created_at)

    按时间倒序则是

    select f.* from t_charge f where not exists (select 1 from t_charge where user_id = f.user_id and created_at > f.created_at) 
  • 相关阅读:
    Django REST framework的解析器与渲染器
    python基础之 数据格式化
    REST framework 之 分页
    Django REST framework 之 认证 权限 限制
    DjangoRestFrameWork 版本控制
    DjangoRESTFrameWork中的视图
    浏览器跨域问题
    初识REST
    vue之生命周期
    vue组件
  • 原文地址:https://www.cnblogs.com/milton/p/6354229.html
Copyright © 2011-2022 走看看