简体   繁体   English

在MySQL中删除除ID之外的所有重复行的最佳方法?

[英]Best way in MySQL to remove duplicated rows grouped by all except ID?

Doesn't seem to be a duplicate coz this question is different. 似乎不是重复因为这个问题是不同的。

My table has 3 columns: id,col2,col3. 我的表有3列:id,col2,col3。 I'm using this method to remove duplicated rows: 我正在使用此方法删除重复的行:

create table temp_table as
select * from my_table where 1 group by col2,col3;

drop table my_table;    
rename table temp_table to my_table;

However, my_table actually has a lot of columns, not just 3, painfully to list out in the query. 但是,my_table实际上有很多列,而不仅仅是3,很难在查询中列出。 So I want to ask whether there's a way that we can do a query something like this: 所以我想问一下,我们是否可以通过以下方式进行查询:

create table temp_table as
select * from my_table where 1 group by * except id;

drop table my_table;    
rename table temp_table to my_table;

Is there a possible way? 有可能吗?

You could do a sub-query to make sure that what you get is unique. 您可以执行子查询以确保您获得的内容是唯一的。 This query will give you the duplicates (preserving the ones with the lower IDs): 此查询将为您提供重复项(保留ID较低的项):

SELECT id
  FROM duplicates d1
 WHERE EXISTS (
    SELECT 1
      FROM duplicates d2
     WHERE d2.col2 = d1.col2
       AND d2.col3 = d1.col3
       AND d2.id < d1.id
)

throw them into a temporary table (or load them to PHP) and run a second query to DELETE . 将它们放入临时表(或将它们加载到PHP)并运行第二个查询到DELETE (You can't modify a table while you're reading from it) (您在阅读时无法修改表格)

Do a WHERE NOT EXISTS to get the IDs of the elements to preserve (again, the ones with the lowest IDs are kept). 执行WHERE NOT EXISTS以获取要保留的元素的ID(同样,保留具有最低ID的元素)。

I found a method to "remove duplicated rows grouped by all except ID" but it's not purely MySQL, requires additional PHP code and damn long: 我发现了一种方法来“删除除ID之外的所有重复行”,但它不是纯粹的MySQL,需要额外的PHP代码并且该死的:

$mysqli = mysqli_connect(...);

function remove_duplicated_rows($table_name) {
  global $mysqli;

  //get column list
  $query = "describe $table_name";
  $result = mysqli_query($mysqli,$query);
  $rows = mysqli_fetch_all($result,MYSQLI_ASSOC);
  $columns = array();
  foreach ($rows as $row)
    if (strtolower($row["Field"])!="id")
      array_push($columns,$row["Field"]);
  $column_list = implode(",",$columns);

  //create temp table
  $temp_table = $table_name."_temporary_table";
  $query = 
  "create table $temp_table as ".
  "select * from $table_name where 1 group by $column_list";
  mysqli_query($mysqli,$query);

  //drop old table
  $query = "drop table $table_name";
  mysqli_query($mysqli,$query);

  //rename temp table to old table
  $query = "rename table $temp_table to $table_name";
  mysqli_query($mysqli,$query);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM