sql - Mysql, update query -


i have table this:

table1

first_id    second_id    value  1           0            10  2           0            60 <- can bad value, need update  2           12           30  2           14           30  3           0            50  4           0            100 <- can bad value, need update  4           20           50  4           41           30  4           33           20 

i need update rows have second_id = 0 , in table exists rows same first_id second_id != 0. need update rows sum of rows have same first_id , second_id != 0.

for example:

first_id = 3 , second_id = 0 => not update, 0 rows first_id = 3 , second_id != 0  first_id = 4 , second_id = 0 => update, sum(50,30,20) = rows same first_id , second_id != 0 

how can in 1 update statement?

i tried sth without effect (problem recursive query?).

update table1 t1 set t1.value =  (      select sum(t2.value)      table1 t2      t2.second_id != 0 , t2.first_id = t1.first_id ) t1.second_id = 0 ,  (     select count(*)      table1 t3      t3.first_id = t1.first_id ) > 1 

mysql doesn't let update same table you're running select statement on. have subquery , alias result temporary table, , join on that.

update table1 tbl1     join (select t2.first_id, sum(t2.the_value) thevalue table1 t2 t2.second_id != 0 group t2.first_id) tbl2 on tbl2.first_id = tbl1.first_id set tbl1.the_value = tbl2.thevalue tbl1.second_id = 0; 

demo

in demo, initialized value columns of marked 1 can see updated desired value.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -