下面的MySQL语句根据ADDRESS1和POSTCODE选择所有重复的行,其中最新行INSPECTION_DATE。本质上,它会选择我想要保留的所有内容。
SELECT COUNT(*), MAX(INSPECTION_DATE), ADDRESS1, POSTCODE, id
FROM epc
GROUP BY ADDRESS1, POSTCODE
HAVING COUNT(*) > 1;
我的问题是,如何删除所有较旧的重复项,并保留上述语句返回的重复项。
答案 0 :(得分: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;
更新 http://sqlfiddle.com/#!9/8de866/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));