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) 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM