欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

完美的【去重留一】SQL

程序员文章站 2023-11-28 08:09:16
上面这条sql语句,仔细看一下,揣摩出思路也不难,大概也分为3步来理解: 根据条件,删除原表中id大于t2中id的记录 ......

 

delete consum_record
from
 consum_record, 
 (
  select
   min(id) id,
   user_id,
   monetary,
   consume_time
  from
   consum_record
  group by
   user_id,
   monetary,
   consume_time
  having
   count(*) > 1
 ) t2
where
 consum_record.user_id = t2.user_id 
 and consum_record.monetary = t2.monetary
 and consum_record.consume_time = t2.consume_time
and consum_record.id > t2.id;

上面这条sql语句,仔细看一下,揣摩出思路也不难,大概也分为3步来理解:

(select min(id) id, user_id, monetary, consume_time from consum_record group by user_id, monetary, consume_time having count(*) > 1 ) t2 查询出重复记录形成一个集合(临时表t2),集合里是每种重复记录的最小id
consum_record.user_id = t2.user_id and consum_record.monetary = t2.monetary and consum_record.consume_time = t2.consume_time 关联 判断重复基准的字段

根据条件,删除原表中id大于t2中id的记录