将重复的选择转换为更新

时间:2016-06-15 20:24:19

标签: mysql join duplicates updates

我已设法通过以下方式选择每个重复记录的计数和ID:

select T1.ID,T2.Count
from MyTable T1
join (SELECT ID,Count(*) as Count FROM MyTable 
where Field_C=X 
and Field_S=Y  
group by NumberField,NameField having count(*)>1) T2 
on T1.NumberField=T2.NumberField
and T1.NameField = T2.NameField

这将返回我想要更新的记录的ID(T1.ID)以及我想用(T2.Count)更新CountField的值。

只是不确定如何在到目前为止更改为更新。

2 个答案:

答案 0 :(得分:0)

如果您已经选择了这样的更新

    UPDATE MyTable T1
    join (SELECT ID,Count(*) as Count FROM MyTable 
    SET T1.ID = T2.Count
    where Field_C=X 
    and Field_S=Y  
    group by NumberField,NameField having count(*)>1) T2 
    on T1.NumberField=T2.NumberField 

答案 1 :(得分:0)

我想在办公室度过了漫长的一天,但这很容易解决。我认为让第一个选择让我离开,直到我意识到我需要完全摆脱它,因为我没有选择但更新:

Update MyTable T1
join (SELECT ID,Count(*) as Count FROM MyTable 
where Field_C=X 
and Field_S=Y  
group by NumberField,NameField having count(*)>1) T2 
on T1.NumberField=T2.NumberField
and T1.NameField = T2.NameField
Set T1.CountField=T2.Count