如何检查和删除所有重复项

时间:2013-11-10 22:12:58

标签: mysql sql

表格示例

 id  name       value 1    value 2
 1   disco      numeber 1  0
 2   disco      numeber 2  0
 3   cheese     numeber 3  0
 4   something  numeber 4  0
 5   something  numeber 5  0

我想要一个代码来删除所有具有重复名称的行,并且只留下唯一的值。

结果应为

 id  name       value 1    value 2
 1   disco      numeber 1  0
 3   cheese     numeber 3  0
 4   something  numeber 4  0

我有这段代码

delete from your_table 
 where id not in 
select * from 
( select min(id) 
   from your_table 
  group by user_id, badge_id ) x ) 

但它不起作用

1 个答案:

答案 0 :(得分:0)

您可以使用JOIN

进行操作
DELETE t FROM table1 t JOIN
(
  SELECT name, MIN(id) id
    FROM table1
   GROUP BY name
) q 
    ON t.name = q.name 
   AND t.id <> q.id;

这是 SQLFiddle 演示

或使用子查询

DELETE FROM table1
 WHERE id NOT IN
(
  SELECT id
    FROM
  (
    SELECT MIN(id) id
      FROM table1
     GROUP BY name
  ) q
);

这是 SQLFiddle 演示