我有一个表,其中一列有多个重复的行。所以我想清除重复的数据。
事件表:
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
个插入,N
个更新和1
个删除事件行。因此,我想删除N-1
更新事件,但不会删除最后一个事件。
例如,在此表中,对于data_id=1
,更新事件为2,3,5
。我想删除2
和3
,但不要删除5
。因为5
是最后更新。
答案 0 :(得分:0)
我会这样写:
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';
答案 1 :(得分:0)
具有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
)