php - Mysql: Delete duplicate records based on minimum amount -


i need delete duplicate records based on minimum amount same order number. table has 100k records , structure this. tmp_id primary key in table.

------------------------------------ user_id   order_number amount  tmp_id ------------------------------------- 15         12364        25      1 20         454544       75      2 4          12364        100     3 6          45487        45      4 8          454544       330     5 

i tried delete minimum amount of duplicate records using

$qb_duplicate_data_query="select user_id,order_number,amount tmp_qbappraiser limit 10";  $qb_duplicate_data_sql=mysql_query($qb_duplicate_data_query) or die(mysql_error());  while($row=mysql_fetch_array($qb_duplicate_data_sql)) {      $amount=$row['amount'];      $order_no=$row['order_number'];       $sql="select c1.tmp_id tmp_qbappraiser c1 inner join (select tmp_id tmp_qbappraiser order_number='$order_no' order amount asc) c  on c.tmp_id=c1.tmp_id group c1.order_number having count(order_number)>1";       $query=mysql_query($sql) or die(mysql_error());       $result=mysql_fetch_array($query);       $db_tmp_id=$result['tmp_id'];       if($db_tmp_id!='') {          $delete_sql="delete tmp_qbappraiser order_number='$order_no' , tmp_id='$db_tmp_id'";           $delete_query=mysql_query($delete_sql) or die(mysql_error());      }  } 

when execute code lock wait timeout exceeded try restarting transaction error. how optimize query or there other way delete thousands of records?

you not need write multiple queries deleting duplicate entry, done 1 single query.

delete t1 tmp_qbappraiser t1 join tmp_qbappraiser t2 on t1.order_number = t2.order_number , t1.amount < t2.amount ; 

the above query keep max amount per order_number , delete rest.

you may need add indexes in table making faster

alter table tmp_qbappraiser add index ord_amt_idx(order_number,amount); 

note: make sure take backup of table before applying index , running delete query.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -