I need to remove all rows having duplicated title column. Something like:
delete from clients where title is duplicated
For example, if five rows have the same title column - four of them shold be deleted.
How to do this?
I need to remove all rows having duplicated title column. Something like:
delete from clients where title is duplicated
For example, if five rows have the same title column - four of them shold be deleted.
How to do this?
If you have a unique column like id or somedate:
delete c
from clients c inner join clients cc
on cc.title = c.title and cc.id < c.id
This code will keep the row with the minimum id among the duplicates.
See the demo.
Assuming you clients table have as pk the column id delete all the rows wotn same title but with id <> from max(id)
delete c
from clients c
LEFT JOIN (
select max(id) max_id, title
from clients
group by title
) t on t.title = c.title
and t.max_id = c.id
where t.max_id is null
#1054 - Unknown column 't._max_id' in 'where clause'For completeness, I give a solution for a table without a primary/unique key:
delete c
from clients c
cross join (select @titles := '') init
where find_in_set(sha2(title, 224), @titles) or
length(
@titles := concat(
@titles, ',', sha2(title, 224)
)
) < 0;
Test it online with db-fiddle.com.