如何按列表单数据库删除重复数据[重复]

问题描述 投票:0回答:2

我有一个表,一列有多个重复的行。所以我想清除重复的数据。

活动表:

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。我想删除23但不是5。因为5是最后更新。

sql postgresql duplicates sql-delete postgresql-9.5
2个回答
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
  )

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';
© www.soinside.com 2019 - 2024. All rights reserved.