Mysql,更新查询

Mysql,更新查询,mysql,sql,Mysql,Sql,我有这样的桌子: 表1 first_id second_id value 1 0 10 2 0 60 <- can be bad value, need update this 2 12 30 2 14 30 3 0 50 4 0

我有这样的桌子:

表1

first_id    second_id    value
 1           0            10
 2           0            60 <- can be bad value, need update this
 2           12           30
 2           14           30
 3           0            50
 4           0            100 <- can be bad value, need update this
 4           20           50
 4           41           30
 4           33           20
如何在一个update语句中实现这一点

我试过这样的方法,但没有效果(递归查询有问题?)


我了解到您不能基于即时子查询进行更新。这就是为什么在下面的查询中会看到嵌套的子查询

UPDATE table1 t1 
    INNER JOIN table1 t2
    ON t1.first_id = t2.first_id and t2.second_id != 0
    SET t1.value = (SELECT total_value from (SELECT first_id, SUM(value) total_value FROM table1 WHERE second_id != 0 GROUP BY first_id) as t2 WHERE t2.first_id = t1.first_id)
    WHERE t1.second_id = 0;
参考资料


  • MySQL不允许您更新正在运行
    SELECT
    语句的同一个表。因此,您必须执行子查询,然后将结果别名为临时表,并在此基础上加入
    JOIN

    UPDATE table1 tbl1
        JOIN (SELECT t2.first_id, SUM(t2.the_value) as theValue FROM table1 t2 WHERE t2.second_id != 0 group by t2.first_id) tbl2 ON tbl2.first_id = tbl1.first_id
    SET tbl1.the_value = tbl2.theValue
    WHERE tbl1.second_id = 0;
    


    在演示中,我初始化了标记为1的值列,以便您可以看到它们被更新为所需的值。

    这不是必需的,因为我正在选中>1而不是>=1。问题是,我的查询给了我一个错误:“您不能在FROM子句中为update指定目标表‘t1’”,似乎您必须进行联接。检查这个问题-不客气,可能重复@Łukasz。如果它解决了您的问题,请不要忘记单击答案旁边的复选标记,将其标记为已接受答案:)
    UPDATE table1 t1 
        INNER JOIN table1 t2
        ON t1.first_id = t2.first_id and t2.second_id != 0
        SET t1.value = (SELECT total_value from (SELECT first_id, SUM(value) total_value FROM table1 WHERE second_id != 0 GROUP BY first_id) as t2 WHERE t2.first_id = t1.first_id)
        WHERE t1.second_id = 0;
    
    UPDATE table1 tbl1
        JOIN (SELECT t2.first_id, SUM(t2.the_value) as theValue FROM table1 t2 WHERE t2.second_id != 0 group by t2.first_id) tbl2 ON tbl2.first_id = tbl1.first_id
    SET tbl1.the_value = tbl2.theValue
    WHERE tbl1.second_id = 0;