SQLite: Delete all of rest duplicate records?

时间:2018-12-03 13:17:21

标签: sql sqlite

query that return all unique (not duplicate) records:

select distinct notificationDate, ownerKey 
FROM notification_invoice 
where notificationDate >= 1536019200000 
and providerId in ("1234","567") 

Now I need query that delete all rest (duplicate) inverse records in this table. How I can do this in sqlite?

2 个答案:

答案 0 :(得分:0)

假设_id是主键,则以下查询将删除所有多余的重复项:

DELETE FROM notification_invoice t1
WHERE notificationDate >= 1536019200000 
  and providerId in ("1234","567") 
  AND EXISTS (
     SELECT 1 FROM notification_invoice t2
     WHERE t2.notificationDate = t1.notificationDate 
       and t1.ownerKey = t2.ownerKey 
       and providerId in ("1234","567") 
       AND t1._id < t2._id
  )

答案 1 :(得分:-1)

基于提供的信息,_id是主键。

您可以删除所有_id不是每个通知日期,所有者密钥的最大(_id)值的记录

delete
  from notification_invoice a
where a._id not in (select max(b._id)
                      FROM notification_invoice b
                     where b.notificationDate >= 1536019200000 
                       and b.providerId in ("1234","567") 
                    group by b.notificationdate
                         ,b.ownerKey
                   )