mysql - 从另一个表中的多行更新 MYSQL 表
问题描述
我正在尝试通过求和来从表 xx结果中更新表 yy 。
例如(语法是抽象的):
update table_yy
set sum_of_x_and_y = (
(select sum(row_x) from table_xx where class_id=1)
+
(select sum(row_y) from table_xx where class_id=1) )
表二十
row_id class_id row_x row_y
1 1 4 5
2 1 5 6
3 2 6 7
4 1 7 8
表 yy
class_id sum_of_x_and_y
1 35
2 13
但是我不想手动设置class_id,而是想做一些像内部连接更新这样的事情,但我正在处理15k+的记录。
解决方案
这是一个应该完成这项工作的查询
UPDATE table_yy, (
SELECT class_id, SUM(table_xx.row_x + table_xx.row_y) AS sum_of_x_and_y
FROM table_xx
GROUP BY table_xx.class_id
) AS table_sum
SET table_yy.sum_of_x_and_y = table_sum.sum_of_x_and_y
WHERE table_yy.class_id = table_sum.class_id
推荐阅读
- static - 我可以在 for 语句中调用 jekyll 页面属性吗
- google-bigquery - 在 BQ 中连接不同位置的两个数据集
- c++ - 匹配表达式,但不匹配以 # 开头的行
- java - Including nested objects in the JSON of a Spring Boot application
- html - 以两种方式更新选中的单选按钮
- python - ValueError:无法分配“'x'”:“y”必须是“z”实例
- css - 如何在反应中使用两个api url
- javascript - require('fs') 不起作用,不知道为什么控制台说有错误
- c++ - C++[错误] 不能传递非平凡可复制类型的对象'std::string {aka class std::basic_string
}' 通过 '...' - tensorflow - 如何在多个没有 GPU 的设备上训练 TensorFlow?