MySQL - 使用 SET 语句的 UPDATE 查询取决于前一个 SET 语句的结果

MySQL - UPDATE query with SET statement dependent on the outcome of the previous SET statement(MySQL - 使用 SET 语句的 UPDATE 查询取决于前一个 SET 语句的结果)
本文介绍了MySQL - 使用 SET 语句的 UPDATE 查询取决于前一个 SET 语句的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我希望通过 UPDATE 语句实现的目标的表格表示形式.

Here is a tabular representation of what I would like to achieve with an UPDATE statement.

+----+----+---+---+----+----------+---------------+---------------+
| ID | A  | B | C | D  |  Calc A  |    Calc B     |    Calc C     |
+----+----+---+---+----+----------+---------------+---------------+
|  1 |  6 | 5 | 2 | 10 | =[A]-[B] | =[Calc A]/[D] | =[B]/[Calc B] |
|  2 |  8 | 5 | 2 | 10 | =[A]-[B] | =[Calc A]/[D] | =[B]/[Calc B] |
|  3 | 10 | 5 | 2 | 10 | =[A]-[B] | =[Calc A]/[D] | =[B]/[Calc B] |
+----+----+---+---+----+----------+---------------+---------------+

实现此目的的当前 UPDATE 语句如下...

My Current UPDATE statement to achieve this is as follows...

UPDATE [EXAMPLE]
SET [Calc A]    = A - B
    , [Calc B]  = [Calc A] / D
    , [Calc C]  = B / [Calc B] 

但是它没有按预期工作.[Calc A] 将在第一次更新时正确计算.但是 [Calc B] 将使用 [Calc A] 中的 OLD 值进行计算,而不是我刚刚写入数据库的 NEW 更新值.这适用于 [Calc C],它再次引用 [Calc B] 的 OLD 值.

However it is not working as intended. [Calc A] will calculate correctly on the first UPDATE. However [Calc B] will calculate using the OLD value in [Calc A] and not the NEW updated value I just wrote to the database. This holds true for [Calc C] which again refers to the OLD value of [Calc B].

如果您执行 UPDATE 语句 3 次,数据将正确计算出来.[Calc A] 在第一次计算中设置正确,然后 [Calc B] 将在第二次 UPDATE 中引用 [Calc A] 的正确更新值,然后 [Calc C] 将在 [Calc B] 中引用正确的值第三次更新.

If you perform the UPDATE statement 3 times the data will calculate out correctly. [Calc A] is set correctly in the first calculation, then [Calc B] will reference the correct updated value of [Calc A] in the second UPDATE, then [Calc C] will reference the correct value of [Calc B] in the 3rd UPDATE.

所以我的问题是如何在一个更新语句中将所有列设置为正确的值?

So my question is how do I set all the columns to their correct value in ONE update statement?

推荐答案

独立计算即可:

update [EXAMPLE]
set [Calc A] = A - B,
    [Calc B] = (A - B) / D,
    [Calc C] = B / ((A - B) / D)

这篇关于MySQL - 使用 SET 语句的 UPDATE 查询取决于前一个 SET 语句的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)