查找重复项并在MYSQL Server中删除它们

时间:2017-04-10 12:47:56

标签: mysql

我有很多重复的名称,我需要找到并删除它们。 我只想保存 usedpoints 的最高值,并删除 usedpoints 值较低的重复项。

MYSQL表示例:

==============================
| name | points | usedpoints |
|----------------------------|
| john | 840    | 1200       |
| john | 230    | 900        |
| jane | 550    | 400        |
| jane | 130    | 245        |
| nick | 130    | 123        |
| nick | 90     | 200        |
==============================

4 个答案:

答案 0 :(得分:0)

1)如果你想保持id值最低的行:

DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name

2)如果你想保留id值最高的行:

DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name

您可以使用任何其他字段而不是ID。

答案 1 :(得分:0)

您可以使用Row_Number()删除欺骗

;with cte as (
    Select *
          ,RN = Row_Number() over (Partition By Name Order by usedpoints Desc)
     From  YourTable
)
--Delete from cte where RN>1
Select * from cte where RN>1   -- << Remove is satisfied

答案 2 :(得分:0)

use your_schema;

drop table if exists temp_names_values; -- names with max usedpoints will be stored in this table
create temporary table temp_names_values as (select name,max(usedpoints ) as mx from test group by name);

drop table if exists temp_max_ids ; -- record ids of names with max usedpoints will be stored in this table
create temporary table temp_max_ids  as (select test.idtest from test,temp_names_values where (test.name = temp_names_values.name and test.usedpoints = temp_names_values.mx));

select * from test where test.idtest not in (select idtest from temp_max_ids )

我认为表名是test。 最后一个select语句实际上是你应该编写delete语句的地方。

答案 3 :(得分:0)

select o.name, oc.dupeCount, o.usedpoints from MyTable o inner join ( SELECT name, COUNT(*) AS dupeCount FROM MyTable GROUP BY name HAVING COUNT(*) > 1 ) oc on o.name = oc.name

我有这个找到重复,但现在我需要删除它们..