删除重复行,按max(datetime)保留最近的行

elcex8rz  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(438)

下面的mysql语句根据address1和postcode选择所有具有重复项的行,其中最近的一行是inspection\u date。基本上,它选择了所有我想要保留的。

SELECT COUNT(*), MAX(INSPECTION_DATE), ADDRESS1, POSTCODE, id
FROM epc 
GROUP BY ADDRESS1, POSTCODE 
HAVING COUNT(*) > 1;

我的问题是,如何删除所有旧的副本,保留上面语句返回的那些副本。

oxiaedzo

oxiaedzo1#

http://sqlfiddle.com/#!9月8日DE866/1

DELETE  e
FROM epc e
INNER JOIN epc max_
ON e.address1 = max_.address1
   AND e.postcode = max_.postcode
   AND e.inspection_date < max_.inspection_date;

updatehttp://sqlfiddle.com/#!9/5bd5981/1号

DELETE  e
FROM epc e
INNER JOIN epc max_
ON e.address1 = max_.address1
   AND e.postcode = max_.postcode
   AND (e.inspection_date < max_.inspection_date
        OR (e.inspection_date = max_.inspection_date
           AND e.id < max_.id));

相关问题