[英]SQL update execution order matters?
我一直認為在SQL UPDATE
期間,現有值將保持不變,直到整個更新語句完成,但我在實踐中看到不同的行為。
Inventory
-----------------------------
date base flexible
2014-05-01 5 10
2014-05-02 5 10
UPDATE Inventory SET base = GREATEST(0, base - 7), flexible = flexible - GREATEST(0, (7 - base)) WHERE date = '2014-05-01'
UPDATE Inventory SET flexible = flexible - GREATEST(0, (7 - base)), base = GREATEST(0, base - 7) WHERE date = '2014-05-02'
Inventory
-----------------------------
date base flexible
2014-05-01 0 3
2014-05-02 0 8
在第一個示例中,似乎使用第一個表達式將base
更新為零,導致第二個表達式不正確地計算(7 - 0)
而不是(7 - 5)
。
誰能解釋一下這里發生了什么?
MySQL打破了標准;
它使用當前字段值更新列,考慮更新中的字段順序,而不是遵循使用更新語句之前的字段值的SQL標准。
來自文檔 ;
如果從表中訪問要在表達式中更新的列,UPDATE將使用列的當前值。 以下語句中的第二個賦值將col2設置為當前(更新的)col1值,而不是原始col1值。 結果是col1和col2具有相同的值。 此行為與標准SQL不同。
UPDATE t1 SET col1 = col1 + 1,col2 = col1;
您將在提交之前看到自己的更改,而其他人則不會。
看看這個 。 我認為這是因為GREATEST功能......
如何將base
值存儲在用戶變量中,如下所示:
UPDATE Inventory
SET base = (@base := base), flexible = (@flexible := flexible),
base = GREATEST(0, @base - 7),
flexible = @flexible - GREATEST(0, (7 - @base));
這是測試:
mysql> insert into Inventory values('2014-05-01', 5, 10);
Query OK, 1 row affected (0.00 sec)
mysql> insert into Inventory values('2014-05-02', 5, 10);
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> UPDATE Inventory
-> SET base = (@base := base), flexible = (@flexible := flexible),
-> base = GREATEST(0, @base - 7),
-> flexible = @flexible - GREATEST(0, (7 - @base));
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> SELECT * FROM Inventory;
+------------+------+----------+
| date | base | flexible |
+------------+------+----------+
| 2014-05-01 | 0 | 8 |
| 2014-05-02 | 0 | 8 |
+------------+------+----------+
2 rows in set (0.00 sec)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.