这个问题在这里已有答案:
我有一个表,一列有多个重复的行。所以我想清除重复的数据。
活动表:
event_id, event_type, data_id, data date
1 insert 1 x 06.03.2019 13:04
2 update 1 x1 06.03.2019 13:05
3 update 1 x11 06.03.2019 13:06
4 insert 2 y 06.03.2019 13:07
5 update 1 x111 06.03.2019 13:08
6 delete 1 x111 06.03.2019 13:09
7 update 2 y1 06.03.2019 13:10
8 update 2 y11 06.03.2019 13:11
9 update 2 y11 06.03.2019 13:12
每个数据id都有1
insert,N
update和1
删除表中的事件行。所以我想删除N-1
更新事件,但不会删除最后一个事件。例如,在此表中,对于data_id=1
更新事件是2,3,5
。我想删除2
和3
但不是5
。因为5
是最后更新。
有EXISTS:
delete from tablename t
where
event_type = 'update'
and exists (
select 1 from tablename
where
data_id = t.data_id
and
event_type = 'update'
and
event_id > t.event_id
)
我会把它写成存在:
DELETE
FROM your_table t1
WHERE EXISTS (SELECT 1 FROM your_table t2
WHERE t1.data_id = t2.data_id AND
t2.event_id < t1.event_id AND
t2.event_type = 'update') AND
t1.event_type = 'update';