假设我有一个名为
var
的表,其中包含foo
和bar
两列,这两列都是整数,当前值为0。如果我运行:
UPDATE var SET foo=foo+1, bar=foo+1
那么bar
的值将是什么?是1还是2?如果我更改顺序会发生变化吗?
UPDATE var SET bar=foo+1, foo=foo+1
UPDATE
文档指出了这一点,说明每个列更新的表达式将按声明的顺序进行评估,并且始终使用列的“当前”值:
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 setscol1
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 originalcol1
value. The result is thatcol1
andcol2
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.
对于 UPDATE var SET foo=foo+1, bar=foo+1
,foo
将会被设置为 foo+1
,然后 bar
的更新将使用 foo+1
中新设置的值。
值得注意的是,这种行为与 SQL 标准不同,SQL 标准指示所有列更新应在“同时”概念上发生。
update test set foo=foo+1, bar=foo+1, foo=bar+1;
顺便提一下,这里还有另一个有用的MySQL技巧:
insert into test (foo, bar) values ('some text', MD5(foo));
注意 - 对于PostgreSQL,查询使用查询开始时的值执行,而不是在查询执行过程中动态更改的值。
create table test (
field1 int2 default 0,
field2 int2 default 0
);
insert into test values (1, 2);
update test set field1 = field2, field2 = field1 +1;
select * from test;
结果:
field1, field2
2,2
无论顺序如何,foo=1,bar=1 [编辑:在MS-SQL中。 (显然是我的MySQL错误)]
bar
等于 2) - kmoney12