繁体   English   中英

在单个mysql查询中将一些金额从一列转移到同一表的另一列

[英]transfer some amount from one column to another of same table in single mysql query

我有桌子

ID | Amount
-------------
1  | 500
2  | 800
3  | 200

我如何使用其ID将300从第二行转移到第一行,我可以通过存储过程来完成,有没有办法在单个查询中执行此操作

MySql计算布尔表达式为1或0,因此可以使用:

update tablename
set amount = amount + (id = 1) * 300 - (id = 2) * 300
where id in (1, 2);

要么:

update tablename
set amount = amount + ((id = 1) - (id = 2)) * 300
where id in (1, 2);

参见演示
结果:

| ID  | Amount |
| --- | ------ |
| 1   | 800    |
| 2   | 500    |
| 3   | 200    |

您可以尝试以下方法:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM