2017-04-10 53 views
0

我有很多重复,我需要找到并删除它们。 我要救的usedpoints只有最高值,并用usedpoints较低的值删除重复。查找重复和MySQL服务器删除它们

MySQL表举例:

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

是否您在SQL Server或MySQL这样做呢?标签与标题不匹配。 – Becuzz

+0

对不起,MySQL的(编辑) – Razvan

回答

1

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。

+0

我不明白..删除名字从mytable的 – Razvan

+0

检查:http://stackoverflow.com/questions/4685173/delete-all-duplicate-rows-except-for-one-in -mysql – Jenish

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 
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) 

我认为,表名是考验。 最后的select语句实际上是你应该写你的delete语句。

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 

我有这样的查找重复,但现在我需要将其删除..