Mysql:根据最小金额删除重复记录

时间:2015-06-26 11:01:40

标签: php mysql

我需要根据同一amount的最小order number删除重复记录。表有100k记录,结构是这样的。 <{1}}在此表中为tmp_id

primary key

我尝试使用

------------------------------------ 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 最少量的重复记录。{
delete

当我执行此代码时,出现$qb_duplicate_data_query="select user_id,order_number,amount from 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 from tmp_qbappraiser c1 inner join (SELECT tmp_id FROM tmp_qbappraiser WHERE order_number='$order_no' ORDER BY amount asc) AS c on c.tmp_id=c1.tmp_id GROUP BY 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 from tmp_qbappraiser where order_number='$order_no' and tmp_id='$db_tmp_id'"; $delete_query=mysql_query($delete_sql) or die(mysql_error()); } } 错误。如何优化我的查询或有没有其他方法来删除数以千计的记录?

1 个答案:

答案 0 :(得分:1)

您不需要编写多个查询来删除重复条目,这可以通过一个查询来完成。

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

以上查询将保留每order_number的最大金额,并将删除其余的。

您可能需要在表格中添加一些索引才能加快速度

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

注意:确保在应用索引并运行删除查询之前备份表。