【问题标题】:how to update table rows using calculated results from another table in mysql [duplicate]如何使用mysql中另一个表的计算结果更新表行[重复]
【发布时间】:2016-05-02 10:13:37
【问题描述】:

我正在尝试通过汇总桥表 TransactionRecords 的结果来更新 Transactions 表中的 SubTotal 字段。以下是我的表格包含的内容。

|  Transaction  |
| ID | SubTotal |
| 1  |  ???     |
| 2  |  ???     |
| 3  |  ???     |


|     TransactionRecords                      |
| TransactionID | ProductID | QTY | SalePrice |
| 1             |  10       |  4  | 19.99     |
| 2             |  5        |  8  | 9.99      |
| 2             |  3        |  12 | 14.99     |

我想要的是让 Transaction.SubTotal 等于 TransactionRecords.SalePrice * TransactionRecords.QTY 其中 TransactionRecords.TransactionID 等于 Transaction.ID

这个查询:

select TransactionID, sum(UnitPrice * QuantitySold) 
from TransactionRecord 
group by TransactionID;

给我每笔交易和每笔交易中的销售额,这就是我希望 Transaction 表在其适当的 ID 中具有的值。

【问题讨论】:

  • 请你给我们一个你得到的结果的例子吗?
  • @jmj 什么例子?查询?表格中的数据?

标签: mysql sql subquery


【解决方案1】:

试试这个:

UPDATE Transaction t 
SET SubTotal = (SELECT SUM(UnitPrice * QuantitySold) FROM TransactionRecord tr WHERE tr.TransactionId = t.ID);

【讨论】:

  • 谢谢,但我发现了问题,有一些 SUM 结果返回 null,因为它在 TransactionRecords 表中没有记录。
猜你喜欢
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多