Mysql如何去重


MySQL對數據去重的方法

 

在使用 MySQL 存儲數據的時候,經常會遇到 table 中存在重復數據的情況,這個時候,我們就對 table 進行去重,我這里對常用的 MySQL 去重方法做一個簡單的總結。

distinct

select distinct key from table

select distinct key1, key2 from table

語法非常簡單,就是針對 table 進行去重操作,統計出所有不同的 key ,並將結果返回;如果傳入兩個 key 的時候,除去的僅僅是兩個 key 都相同的部分。而且這條 sql 並不會對 table 產生修改,只會返回目標數據key(其他字段的數據也不會返回)

利用 group 進行去重

select key from table group by key having count(*)>1

查詢單個字段重復數據

select * from table t where(t.key1,t.key2)in(select key1,key2 from table group by key1,key2 having count(*)>1);

查詢多個字段的重復數據,並將結果的所有字段信息返回

 

1

2

3

4

5

6

7

8

9

delete from table where key in(

            select t.key from(

                elect key from table group by key having count(*)>1

            )

        )and id not in(

            select t.id from(

                select max(id) as id from table group by id having count(*)>1

            )

        )

刪除 table 中重復數據,其實這個思路很簡單,對 table 按 key 進行分組統計並計數,將 count 大於 1 的組,僅保留 id 最大的那條數據,其余全部刪除。id 一般是主鍵。


免責聲明!

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



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