多表更新(MySQL)
我有一个关于多表更新(MySQL)的问题。考虑表 t1 和 t2。 t1 的 PKEY 是“tid”,它是 t2 中的外键。 t2 中有一个字段“qtyt2”,它依赖于表 t1 中名为“qtyt1”的字段。考虑以下 SQL 语句:
UPDATE t2,t1
SET t2.qtyt2=IF(( t2.qtyt2- t1.qtyt1 )<0,0,( t2.qtyt2- t1.qtyt1 ) ),
t1.qtyt1 ="Some value.."
WHERE t2.tid="some value.."
AND t2.tid=t1.tid
在本例中,qtyt2 依赖于 qtyt1 进行更新,并且后者本身也被更新。现在,如果更新了两行,结果应返回 2。
是否保证字段将按照它们在语句中出现的顺序进行更新(首先设置 qtyt2,然后设置 qtyt1)?
是否有可能先设置qtyt1,然后设置qtyt2?
语句中表的顺序重要吗(UPDATE t2, t1 或 UPDATE t1,t2)?
我发现如果我写“UPDATE t1,t2”,那么只有 t1 会得到更新,但将语句更改为“UPDATE t2,t1”时,一切正常。
I have a question regarding multi-table update(MySQL). Consider table t1 and t2. The PKEY for t1 is 'tid' which is a foreign Key in t2. There is a field "qtyt2" in t2 which depends on a field called "qtyt1" in table t1. Consider the following SQL statement:
UPDATE t2,t1
SET t2.qtyt2=IF(( t2.qtyt2- t1.qtyt1 )<0,0,( t2.qtyt2- t1.qtyt1 ) ),
t1.qtyt1 ="Some value.."
WHERE t2.tid="some value.."
AND t2.tid=t1.tid
In this example qtyt2 depends on qtyt1 for update and the latter itself is updated.Now the result should return 2 if two rows are updated.
Is there a guarantee that the fields will be updated in the order in which they appear in the statement( first qtyt2 will be set and then qtyt1)?
Is it possible that qtyt1 will be set first and then qtyt2?
Is the order of tables in the statement important (UPDATE t2, t1 or UPDATE t1,t2)?
I found that if I wrote "UPDATE t1,t2" then only t1 would get updated, but on changing the statement to "UPDATE t2,t1" everything worked correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,始终建议明确您的 JOIN。第二,我认为你的条件有一个拼写错误,应该是
WHERE t2.qtyt2='Some value..'
。所以:如果上面是你的意思,那么我相信应该发生的事情是 SQL 将找到
t2.qtyt2="Some value.."
的行集,然后它将更新 t2。 qtyt2,然后它将所有 t1.qtyt1(在行集中)设置为“Some value..”(而不是 t2.qtyt2 的新值)。First off, it is always advisable to make your JOINs explicit. And 2nd, I think your condition has a typo and should be
WHERE t2.qtyt2='Some value..'
. So:If the above is what you mean, then I believe what should be happening is that SQL will find the row set where
t2.qtyt2="Some value.."
, then it will update t2.qtyt2, and then it will set all t1.qtyt1 (in the row set) to "Some value.." (and not the new value of t2.qtyt2).我不相信 MySQL 对更新发生的顺序有任何保证。无论如何,唯一重要的时间是使用具有外键约束的 InnoDB 表时,并且文档明确指出不保证顺序并且更新可能因此失败。在这种情况下,您应该使用单独的更新语句,这应该不是问题,因为您使用 InnoDB 获得的事务是隔离的。
I don't believe MySQL guarantees anything about the order that the updates will occur. The only time that would matter anyway is when using InnoDB tables with foreign key constraints, and the documentation specifically states that the order is not guaranteed and that the update may fail as a result. In that case, you should use separate update statements, which shouldn't be a problem because of the isolation of transactions that you get with InnoDB.
多表语法中不保证顺序。查看 文档。
There is no guarantee of sequence in multi-table syntax. Check out this exerpt from the documentation.