PostgreSQL 更新不返回零计数

发布于 2024-08-10 06:52:43 字数 296 浏览 2 评论 0原文

我尝试一次又一次地用相同的值更新特定记录,但它总是将受影响的行值返回为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

眉黛浅 2024-08-17 06:52:43

无条件设置列的值总是会“影响”它,即使新值与旧值相同。如果您只想查看该值现在是否不同,您可以检查受类似影响的行数,

UPDATE users SET active=1 WHERE id = 304 AND active != 1;

这样更新查询仅匹配尚未“活动”的行

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

UPDATE users SET active=1 WHERE id = 304 AND active != 1;

That way the update query only matches rows which are not already "active"

德意的啸 2024-08-17 06:52:43

您的查询正在更新记录,因此返回 1。

更新不会检查要替换的值是否已存在。

Your query is updating the record, hence returning 1.

Update does not check if the value is replacing is already there.

始终不够 2024-08-17 06:52:43

正如 Schlansker 已经指出的那样,以下内容将满足您的要求。

UPDATE users SET active = 1 WHERE id = 304 AND active <> 1;

但是,不要忘记事务隔离。即,如果两个并行事务正在更新同一行(或者其中一个事务正在删除该行),您可能最终会处于意外状态。这取决于事务隔离级别以及应用程序其余部分的设计方式。

As Schlansker already pointed out the following will do what you're are asking for.

UPDATE users SET active = 1 WHERE id = 304 AND active <> 1;

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文