根据日期和状态在MYSQL中重复

时间:2015-05-06 04:58:26

标签: mysql duplicates updates

这是我目前查找重复电话号码的查询。

SELECT 
    id, cust_num, entry_date 
FROM 
    nums 
GROUP BY 
    cust_num 
HAVING 
    count(*) >= 2 
ORDER BY 
    id 
DESC

然而,现在我希望根据标准一次性更新它们。

我只想更新ID比原版更高的新版本。 并且只有他们具有某种地位。

下面是一个例子,我会根据从数据库中提取的重复项列表来更新。

 ID |  Num | date    | status
  1    555    Sep-12   NEW    (this row wouldnt update first instance of 555)
  33   555    Oct-12   NEW    (this row would update, duplicate with NEW as status)
  42   333    Dec-12   NEW    (this row wouldn't update first instance of 333)
  5    555    Jan-13   ACTIVE (this row wouldnt update, duplicate but wrong status)
  66   333    Feb-14   NEW    (this row would update, duplicate with NEW as status)
  6    555    Jan-13   NEW    (this row would update, duplicate with NEW as status)
  77   333    Mar 15   ACTIVE (this row wouldnt update, duplicate but wrong status)

所以真正的问题是,我会使用什么查询来提取所有重复项,然后根据它们的状态更新它们。

2 个答案:

答案 0 :(得分:0)

num2

在SET语句中添加您想要更新的内容。

答案 1 :(得分:0)

这是选择。和fiddle

的链接
select * from mytable as m where `status` = 'NEW' and exists 
    (select * from mytable as mm where mm.`id` < m.`id` and mm.`num` = m.`num`)

更新状态为更新

update mytable as m set m.`status` = 'UPDATED' where `status` = 'NEW' and exists 
(select * from mytable as mm where mm.`id` < m.`id` and mm.`num` = m.`num`)