更新表 - Mysql

时间:2012-08-03 10:05:46

标签: mysql

enter image description here

需要更新列c2以获取相同c3的所有值。即c3有五个0,前三个0有c在10。在这里,我需要用值10更新记录7和9.最后,c3中的所有0都应该具有相同的c2值,即10

2 个答案:

答案 0 :(得分:1)

您需要self join,然后将列C2更新为:

UPDATE table_name a
       INNER JOIN table_name b
           ON a.C2 = b.C3
SET a.C2 = b.C2
WHERE b.C2 <> 0;

答案 1 :(得分:0)

您如何决定从哪个记录中获取更新其他记录? select c3 from yourTable group by c3将返回您的不同c3值,现在您可以获得每个c3的相应c2值,但是您想如何决定使用哪个值来更新其他值?

编辑:
很少有SQL语句接近:
set @uniqueC3s = (select c3 from yourTable group by c3);
-- loop through the resutlset set @requiredC2Value = (select TOP 1 c2 from yourTable where c3 = @uniqueC3s order by c1);
update yourTable set c2 = @requiredC2Value where c3 = @uniqueC3s;
-- end of loop