2014年4月2日 星期三

在資料庫中找出重複的資料

select 中 group 是把資料相同的欄位群組起來,也意味著那個欄位相同的資料就不會重複出現。

用法: select * from table group by duplicateColumn

把使用過或群組過得資料找出來,就等於找出重複的資料。所以要使用 HAVING count(*) > 1 (資源被使用次數大於 1 )

用法: select * from table group by duplicateColumn HAVING count(*) > 1

但列出的只是那個欄位重複的資料,並無法把所有重複的資料列出。意思是重複的資料已被群組,所以只有一筆。

這時要列出所有重複必須在加上inner join方法

select table.duplicateColumn
from table
inner join (select duplicateColumn from table group by duplicateColumn HAVING count(*) > 1) DUP
on table.duplicateColumn = DUP.duplicateColumn

此時就會列出所有相同的資料。

但想找的是重複又彼此接續的料又如何?
要使用別名成兩個table在比較上下列
select first.*
from table as(可省略) first
left join table next
on first.id = next.id + 1
where first.duplicateColumn = next.duplicateColumn

但問題是第一筆,也就是剛被重複的那筆不會顯示。所以要反向也比
select first.*
from table as(可省略) first
left join table next
on first.id = next.id + 1 and first.id = next.id - 1
where first.duplicateColumn = next.duplicateColumn

此時多出先幾筆資料,沒關係group起來即可。
select first.*
from table as(可省略) first
left join table next
on first.id = next.id + 1 and first.id = next.id - 1
where first.duplicateColumn = next.duplicateColumn group by id