MySQL - UPDATE query with SET statement dependent on the outcome of the previous SET statement

限于喜欢 提交于 2020-01-11 12:04:16

问题


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] |
+----+----+---+---+----+----------+---------------+---------------+

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] 

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

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?


回答1:


Just do the calculations independently:

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



回答2:


I actually found a solution to this problem using local variables in the SET statements. See below.

UPDATE [EXAMPLE]
SET [Calc A]    = @calc_a : = A - B
    , [Calc B]  = @calc_b := @calc_a / D
    , [Calc C]  = B / @calc_b


来源:https://stackoverflow.com/questions/41906511/mysql-update-query-with-set-statement-dependent-on-the-outcome-of-the-previous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!