[英]transfer some amount from one column to another of same table in single mysql query
I have a table 我有桌子
ID | Amount
-------------
1 | 500
2 | 800
3 | 200
How can I transfer 300 from second row to first row using their Id, I can do it by Stored Procedure, is there any way to perform this in single query 我如何使用其ID将300从第二行转移到第一行,我可以通过存储过程来完成,有没有办法在单个查询中执行此操作
MySql evaluates Boolean expressions as 1 or 0, so this will work: MySql计算布尔表达式为1或0,因此可以使用:
update tablename
set amount = amount + (id = 1) * 300 - (id = 2) * 300
where id in (1, 2);
Or: 要么:
update tablename
set amount = amount + ((id = 1) - (id = 2)) * 300
where id in (1, 2);
See the demo . 参见演示 。
Results: 结果:
| ID | Amount |
| --- | ------ |
| 1 | 800 |
| 2 | 500 |
| 3 | 200 |
You can try this: 您可以尝试以下方法:
UPDATE table_users
SET amount = (case when id = 1 then amount+300
when id = 2 then amount-300
end)
WHERE id in (1,2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.