2013-04-29 57 views
3
| id |  name  |    date   |  points | 
| 10 |  Paul  |  2013-04-29 10:15:03  |  2  | 
| 11 |  Joseph  |  2013-04-29 10:50:17  |  0  | 
| 12 |  Joseph  |  2013-04-29 11:23:18  |  10  | 
| 13 |  Bill  |  2013-04-29 11:27:10  |  8  | 
| 14 |  Paul  |  2013-04-29 11:41:38  |  5  | 
| 15 |  Joseph  |  2013-04-29 11:43:15  |  0  | 
| 16 |  Joseph  |  2013-04-29 11:47:30  |  0  | 
| 17 |  Joseph  |  2013-04-29 12:51:38  |  0  | 
| 18 |  Joseph  |  2013-04-29 12:53:58  |  10  | 
| 19 |  Bill  |  2013-04-29 13:17:10  |  8  | 
| 20 |  Joseph  |  2013-04-29 13:21:38  |  7  | 

只有寄存器16和17必须被删除。如何在这种情况下删除重复的行?

我需要的是,每一个有0来自同一用户的序列时,所有相同的序列的缺失,除了第一个0,在这种情况下,ID号15,

+0

是否IDID始终为增量? – Strawberry 2013-04-29 16:42:16

回答

2

假设date领域始终是渐进的,你可以按照下面的过程

  1. 跟踪重复的记录和这些记录
  2. 删除所有具有日期值比最低日期越大,记录的最小日期。

A码例如:

步骤1:

select name, points, count(id) as rowCount, min(id) as minId, min(`date`) as minDate 
from yourTable 
where points = 0 
group by name 
having count(id)>1 

步骤2:

delete from yourTable 
where id in (
    select id 
    from yourTable 
    inner join (
      select name, points, min(id) as minId, count(id) as rowCount, min(`date`) as minDate 
      from yourTable 
      where points = 0 
      group by name 
      having count(id) > 1 
     ) as a on yourTable.name = a.name and yourTable.id > a.minId 
    ) 
and points = 0; 

希望这有助于


我想使用临时表来获取要删除的ID可能很有用:

-- Step 1: Create a temporary table with the names of the people you want to remove 
drop table if exists temp_dup_names; 
create temporary table temp_dup_names 
    select name, points, min(id) as minId, count(id) as rowCount, min(`date`) as minDate 
    from yourTable 
    where points = 0 
    group by name 
    having count(id) > 1; 
alter table temp_dup_names 
    add index idx_name(name), 
    add unique index idx_id(minId); 

-- Step 2: Create a temporary table with the ids you want to delete 
drop table if exists temp_ids_to_delete; 
create temporary table temp_ids_to_delete 
    select distinct a.id 
    from yourTable as a 
    inner join temp_dup_names as b on a.name=b.name and a.id > b.minId 
    where points = 0; 
alter table temp_ids_to_delete 
    add unique index idx_id(id); 

-- Step 3: Delete the rows 
delete from yourTable 
where id in (select id from temp_ids_to_delete); 
-- If MySQL is configured in 'safe mode', you may need to add this 
-- to the where condition: 
-- and id > 0; 
+0

我不明白为什么,但它没有奏效。删除了很多记录,但依然留下了许多相同的用户0。 – Guttemberg 2013-04-29 17:08:11

+0

都是'id'和'date'字段增量? (即,更大的“id”值与更大的“日期”值配对)。我已编辑帖子,以显示使用临时表的分步解决方案。检查步骤2:临时表应具有要删除的ID。如果它没有正确的ID,则必须再次检查步骤1 – Barranka 2013-04-29 17:11:21

+0

是的,ID和日期是增量的 – Guttemberg 2013-04-29 17:15:47