我有一个MySQL表,其行包含重复值text
('a'
和'c'
):
+------+-----+
| text | num |
+------+-----+
| a | 10 |
| b | 10 |
| c | 10 |
| d | 10 |
| c | 5 |
| z | 10 |
| a | 6 |
+------+-----+
所以,我想更新这些行,总结num
的值。之后表格应如下所示:
+------+-----+
| text | num |
+------+-----+
| a | 16 |
| b | 10 |
| c | 15 |
| d | 10 |
| z | 10 |
+------+-----+
UPD:编辑问题。
答案 0 :(得分:5)
将聚合函数SUM
与GROUP BY
子句一起使用。像这样:
SELECT `text`, SUM(num) AS num
FROM YourTableName
GROUP BY `text`;
这会给你:
| TEXT | NUM |
--------------
| a | 16 |
| b | 10 |
| c | 15 |
| d | 10 |
| z | 10 |
答案 1 :(得分:2)
您可以创建一个临时表来临时存储聚合数据,然后从中更新原始表。
示例SQL:
BEGIN;
CREATE TEMPORARY TABLE `table_name_tmp` LIKE `table_name`;
INSERT INTO `table_name_tmp` SELECT `text`, SUM(num) AS num FROM `table_name` GROUP BY 1;
DELETE FROM `table_name`;
INSERT INTO `table_name` SELECT * FROM `table_name_tmp`;
-- COMMIT;
我注释了COMMIT
命令以避免不必要的错误,请在使用前检查结果。