关于mysql:mysql单表多字段update的执行顺序

42次阅读

共计 886 个字符,预计需要花费 3 分钟才能阅读完成。

链接: MySQL 5.6 Reference Manual / UPDATE Statement

针对以下相似 sql

UPDATE t1 SET col1 = col1 + 1, col2 = col1 - 1;

执行后果和从左往右, col1 原值加 1, col2 = 更新后的 col1 减 1(与 col1 原值雷同)

原文

If you access a column from the table to be updated in an expression, UPDATE uses the current value of the column. For example, the following statement sets col1 to one more than its current value:

UPDATE t1 SET col1 = col1 + 1;

The second assignment in the following statement sets col2 to the current (updated) col1 value, not the original col1 value. The result is that col1 and col2 have the same value. This behavior differs from standard SQL.

UPDATE t1 SET col1 = col1 + 1, col2 = col1;

Single-table UPDATE assignments are generally evaluated from left to right. For multiple-table updates, there is no guarantee that assignments are carried out in any particular order.

If you set a column to the value it currently has, MySQL notices this and does not update it.

留神: 对于以上状况, mysql 单表更新赋值通常是从左到右计算的。对于多表更新,不能保障按任何特定的程序执行调配。

同时, 如果 update 赋值前后的后果不变, mysql 不会执行 update, 所以不能通过 sql 的影响行数来判断业务逻辑的执行状况

正文完
 0