美文网首页
MYSQL的UPDATE中SET的执行顺序

MYSQL的UPDATE中SET的执行顺序

作者: rorschachwhy | 来源:发表于2017-06-16 23:55 被阅读0次

    在写UPDATE语句时,发现set多个字段,并且字段有关联关系时,情况会不同:

    第一种情况如下,num可以根据count更新之后的数据来更新,网上搜索“update执行顺序”,也可以找到很多类似的示例:
    update test.new_table set count = count + 1, num = count/2 where id = 1;

    第二种情况,是写的比较复杂的连表更新,排在后面的字段无法根据之前已经更新的字段来更新,查看stackoverflow 和 mysql的官方文档,发现描述如下,结论就是,单表的话mysql会有顺序,后执行的会用先执行的数据来更新,但是多表的话就不再有该顺序:
    https://dev.mysql.com/doc/refman/5.6/en/update.html

    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.

    相关文章

      网友评论

          本文标题:MYSQL的UPDATE中SET的执行顺序

          本文链接:https://www.haomeiwen.com/subject/bsjgxxtx.html