PostgreSQL 更新不返回零计数
我尝试一次又一次地用相同的值更新特定记录,但它总是将受影响的行值返回为 1。
update users set active = 1 where id = 304
1 row(s) affected.
再次进行相同的查询
update users set active = 1 where id = 304
1 row(s) affected.
,但第二次更新应该返回 0 行受影响,对吗?我可以知道如何在最初不更新记录的情况下获得零计数吗?
I tried to update a particular record with same value again and again, but it returns the affected rows value as 1 always.
update users set active = 1 where id = 304
1 row(s) affected.
again the same query
update users set active = 1 where id = 304
1 row(s) affected.
but the second update should return 0 row(s) affected right? May I know how can I get zero count while its not updating the record originally.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无条件设置列的值总是会“影响”它,即使新值与旧值相同。如果您只想查看该值现在是否不同,您可以检查受类似影响的行数,
这样更新查询仅匹配尚未“活动”的行
Unconditionally setting a column's value always "affects" it, even if the new value is the same as the old. If you would like to only see whether the value is now different, you could check the number of rows affected by something like
That way the update query only matches rows which are not already "active"
您的查询正在更新记录,因此返回 1。
更新不会检查要替换的值是否已存在。
Your query is updating the record, hence returning 1.
Update does not check if the value is replacing is already there.
正如 Schlansker 已经指出的那样,以下内容将满足您的要求。
但是,不要忘记事务隔离。即,如果两个并行事务正在更新同一行(或者其中一个事务正在删除该行),您可能最终会处于意外状态。这取决于事务隔离级别以及应用程序其余部分的设计方式。
As Schlansker already pointed out the following will do what you're are asking for.
But, don't forget about transaction isolation. I.e. if two parallell transactions is updating the same row (or if one of them are deleting it) you may end up in an unexpected state. This depends on transaction isolation level and how the rest of the application is designed.