Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete duplicate records without creating a temporary table

Tags:

php

mysql

I have a table with many duplicate records:

shop
ID     tax_id
1      10
1      10
1      11
2      10
2      12
2      10
2      10

I want to delete all duplicate records without creating a temporary table. After the update query, the table should look like:

shop
ID     tax_id
1      10
1      11
2      10
2      12
like image 634
Lina Avatar asked Feb 12 '26 15:02

Lina


1 Answers

Here's an in-place solution (but not one-liner)

Find out max id:

select max(id) as maxid 
  from shop;

Remember this value. Let's say it equals to 1000;

Re-insert unique values, with offset:

insert into shop (id, tax_id) 
select distinct id + 1000, tax_id 
  from shop;

Drop old values:

delete from shop
  where id <= 1000;

Restore normal ids:

update shop
  set id = id - 1000;

PROFIT!

like image 62
Sergio Tulentsev Avatar answered Feb 15 '26 03:02

Sergio Tulentsev