数据库
首页 > 数据库> > mysql-更新列Group by的SUM

mysql-更新列Group by的SUM

作者:互联网

UPDATE table_name SET col3 = SUM(col2) GROUP BY col1

正在给出错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘GROUP BY col1’

如何解决呢?

Col1  | col2  |   col3
Water |   22  |
water |   3   |
water |   5   |
Air   |  10   |
Earth |  3    |
Air   |  5    | 

I want in col3 the results as follows

Col1  | col2  |   col3
Water |   22  |   30
water |   3   |   30
water |   5   |   30
Air   |  10   |   15
Earth |  3    |   3
Air   |  5    |   5

解决方法:

子查询

UPDATE table_name SET col3 = (SELECT SUM(x.col2) FROM (SELECT * FROM table_name) AS x WHERE x.col1 =  table_name.col1)

这将对更新的每一行执行子查询,以获取与col1匹配的每一行的col2之和

问题是,您为什么要这样做?您总是可以根据需要使用SUM来获取此信息.

标签:sum,mysql,group-by
来源: https://codeday.me/bug/20191208/2088626.html