我有一个结构表:
USER_ID | POINTS_BALANCE
10 | 180
10 | 20
10 | 100
10 | 120 如何为所有这些用户将points_balance字段更新为500:
select user_id, sum(points_balance)
from `user_points_table`
group by user_id
having SUM(points_balance) >= 400 && SUM(points_balance) <= 499或者,我可以为having sum(points_balance)介于400和499之间的user_id插入新行吗?
编辑:
例如:
select user_id, sum(points_balance)
from `user_points_table`
where user_id = 74
group by user_id
having SUM(points_balance) >= 400 && SUM(points_balance) <= 499结果:
USER_ID | POINTS_BALANCE
74 | 434 <-- How can I update this result to 500?发布于 2015-12-24 00:17:32
由于要向表中添加新的新行,因此一种选择是使用insert into select
insert into user_points_table
select user_id, 500-sum(points_balance)
from `user_points_table`
where user_id = 74
group by user_id
having SUM(points_balance) >= 400 && SUM(points_balance) <= 499;发布于 2015-12-24 00:14:37
您无法更新派生的信息。如果您希望显示与导出的数字不同的数字,则可以执行以下操作:
select
user_id,
case
when totals < 500 then 500
else totals
end as totals
from (
select user_id, sum(points_balance) as totals
from test
-- where user_id = 10
group by user_id
having totals between 400 and 499
) t
-- where user_id = 10;
+---------+--------+
| user_id | totals |
+---------+--------+
| 10 | 500 |
+---------+--------+如果结果是
select user_id, sum(points_balance) as totals
from test
-- where user_id = 10
group by user_id
having totals between 400 and 499;是
+---------+--------+
| user_id | totals |
+---------+--------+
| 10 | 420 |
+---------+--------+你想把它增加到500,你知道500和420之间的差值是80。因此,插入一条新记录:
insert into test (user_id, points_balance) values (10, 80);或者,您可以将其中一条记录更新为:
update test set points_balance = points_balance + 80
where user_id = 10 and points_balance = 120;接下来的问题是,你会更新10条记录中的哪一条?我希望你有一个唯一标识每一行的id。如果有,请使用最低id更新行。如果您没有唯一标识每一行的字段,这将是创建一个这样的字段的好时机。
为了一次性完成所有这些工作,您可以构建一个存储过程,或者用PHP/Python/任何您喜欢的语言编写脚本。
发布于 2015-12-24 00:28:21
已更新
因为我理解你的问题,你正在寻找一种方法,通过添加差值将每个用户的点数设置为最低500。因此,您的解决方案可能如下所示:
mysql> DELIMITER //;
-> CREATE PROCEDURE updateMinimum()
-> BEGIN
-> DECLARE u,s INT;
-> DECLARE cur CURSOR FOR
-> SELECT user_id, SUM(points) FROM user_points GROUP BY user_id;
-> OPEN cur;
-> read_loop: LOOP
-> FETCH cur INTO u,s;
-> IF s < 500 THEN
-> INSERT INTO user_points (user_id, points) VALUES (u, 500-s);
-> END IF;
-> END LOOP;
-> CLOSE cur;
-> END//
mysql> DELIMITER ;
mysql> CALL updateMinimum();它会告诉你有No data,但别介意--它做到了。只需使用SELECT即可查看:
SELECT user_id, SUM(points) FROM user_points GROUP BY user_id;你可以随时随地使用CALL updateMinimum()。或者,如果您不再需要它,可以通过DROP PROCEDURE updateMinimum();将其删除
https://stackoverflow.com/questions/34439354
复制相似问题