简体   繁体   English

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

[英]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.

相关问题 从一个表中选择单个列的一些数据并插入MySql中的另一个表 - Selecting some data of a single column from one table and insert into another table in MySql MySQL SUBTRACT,使用SUM查询同一列的单表 - MySQL SUBTRACT with SUM Query for One Single Column Same Table 在单个MySQL查询中查找另一张表中一列的值 - In a single MySQL query lookup one column's value in another table MySQL-汇款:将数据从一个字段转移到同一表中的另一个字段 - Mysql - Money transfer: Transfer data from one field to another in the same table 将一些数据从MySQL表的一列移至另一列 - Moving some data from one column of MySQL table to another mysql查询从一个表中选择,以便其列的值不出现在另一表的同一列的值中 - mysql query select from one table such that its column's values are not present in the same column's values in another table SQL查询以传输THE SAME表的另一列上的所有记录 - Sql Query to transfer all records on another column on THE SAME table MYSQL单一查询可从一个表中检索单行,也可从另一表中检索多个行作为单个字段 - MYSQL Single query to retrieve both single row from one table and many rows as a single field from another MYSQL查询-一种基于同一表中另一列中的DISTINCT值从一列返回所有值的简单方法? - MYSQL query - simple way to return all values from one column based on a DISTINCT value in another column in the same table? 使用带有字符串的额外列将数据从一个Mysql表传输到另一个 - Transfer data from one Mysql table to another with an extra column having a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM