Mysql选择复制并标记为重复但排除最新

时间:2016-03-01 08:19:20

标签: mysql duplicates tagging

我想将某个值标记为重复,如果它在我的表中显示多次,但如果它是最新的,它应该排除我行中的最新值。

这是我的表。

ref_id | access
1234     2015-10-04 10:01:10
1234     2015-10-04 10:02:10
1234     2015-10-04 10:03:10

这就是我想要发生的事情

ref_id | access               | tag     
1234     2015-10-04 10:01:10    duplicate
1234     2015-10-04 10:02:10    duplicate
1234     2015-10-04 10:03:10   

1 个答案:

答案 0 :(得分:1)

您可以使用相关子查询来执行此操作:

SELECT ref_id, access, 
       IF((SELECT 1 
           FROM mytable AS t2 
           WHERE t1.ref_id = t2.ref_id AND
                 t2.access > t1.access LIMIT 1) = 1, 'duplicate', '') AS tag
FROM mytable AS t1

Demo here

或者,您可以将JOIN用于具有最大日期值的记录:

SELECT t1.ref_id, access, 
       IF(t1.access < t2.max_access, 'duplicate', '') AS tag
FROM mytable AS t1
INNER JOIN (SELECT ref_id, MAX(`access`) AS max_access 
            FROM mytable
            GROUP BY ref_id
) AS t2 ON t1.ref_id = t2.ref_id

Demo here

UPDATE你可以使用:

UPDATE mytable AS t1
INNER JOIN (SELECT ref_id, MAX(`access`) AS max_access 
      FROM mytable
      GROUP BY ref_id
) AS t2 ON t1.ref_id = t2.ref_id
SET tag = 'duplicate'
WHERE t1.access < t2.max_access;

Demo here