假设date
领域始终是渐进的,你可以按照下面的过程
- 跟踪重复的记录和这些记录
- 删除所有具有日期值比最低日期越大,记录的最小日期。
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;
是否IDID始终为增量? – Strawberry 2013-04-29 16:42:16