我有一张表有多个RFID记录,每个记录都有一个名为time的列,我想要的是删除重复的RFID recods,除了一个有最长时间的记录。
表名是attendance_images(id,RFID,时间,年,月,日),我的查询如下:
DELETE t FROM attendance_images AS t LEFT JOIN (
SELECT max( t1.time ) AS time
FROM attendance_images AS t1
WHERE t1.year=2016
AND t1.month=8
AND t1.day=4
AND t1.time < 120000
GROUP BY t1.RFID
) keep ON t.time = keep.time
WHERE keep.time IS NULL
AND t.year =2016
AND t.month =8
AND t.day =4
AND t.time < 120000
查询效果为(0 rows deleted. (Query took 0.0034 sec)
)但表格根据条件有重复记录。
请帮助解决此问题。
答案 0 :(得分:3)
您还需要匹配RFID
:
DELETE t
FROM attendance_images AS t LEFT JOIN
(SELECT RFID, max( t1.time ) AS time
FROM attendance_images AS t1
WHERE t1.year = 2016 AND t1.month = 8 AND t1.day = 4 AND t1.time < 120000
GROUP BY t1.RFID
) keep
ON t.time = keep.time AND t.RFID = keep.RFID
WHERE keep.time IS NULL AND
t.year = 2016 AND t.month = 8 AND t.day = 4 AND t.time < 120000;
显然,多个RFID
可以拥有相同的最长时间,因此只能加入time
并不起作用。
编辑:
您应该验证您确实要删除数据:
select ai.rfid, max(ai.time), min(ai.time), count(*)
from attendance_images ai
where ai.year = 2016 AND ai.month = 8 AND ai.day = 4 AND ai.time < 120000
group by ai.rfid
having min(ai.time) < max(ai.time);
我的猜测是,这将不会返回任何行,表示您没有这样的重复项。
您可以将having
子句更改为having count(*) > 1
,以查看是否有重复项具有相同的time
值。
编辑II:
查询中值的缩进表明time
存储为字符串,而不是整数。您可以尝试替换条件:
t.time < 120000
使用:
t.time + 0 < 120000