使用 Postgres 8.4 中每行调用一次的函数进行更新
我有以下 UPDATE 语句:
update mytable
set a = first_part(genid()),
b = second_part(genid()),
c = third_path(genid())
where package_id = 10;
在本例中,函数 genid() 为每一行调用三次,这是错误的 - 我希望它为 mytable 的每一行只调用一次。
我正在使用 PostgreSQL 8.4 数据库。如何编写正确的更新?
我已经尝试过类似的方法:
update mytable
set a = first_part(g),
b = second_part(g),
c = third_path(g)
where package_id = 10
from genid() as g;
但它不起作用,因为整个更新语句仅调用了一次。
I have the following UPDATE statement:
update mytable
set a = first_part(genid()),
b = second_part(genid()),
c = third_path(genid())
where package_id = 10;
In this example the function genid()
is called three times for each row, which is wrong - I want it to be called only once for each row of mytable
.
I'm using PostgreSQL 8.4 database. How to write the correct update?
I've tried something like this:
update mytable
set a = first_part(g),
b = second_part(g),
c = third_path(g)
where package_id = 10
from genid() as g;
But it didn't work, because genid()
has been called only once for the whole update statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试过 Postgres 的非标准
UPDATE .. FROM
子句?我想,这会起作用。请注意,我强制在子选择内的
mytable
中为每个记录调用一次genid()
。然后,我使用假设的id
列自连接mytable
和gen
。请参阅此处的文档:
http://www.postgresql.org/docs /current/interactive/sql-update.html
不过,这似乎仅在 Postgres 9.0 中引入。如果这看起来太复杂(即不太可读),您仍然可以求助以用户身份登录 pgplsql 此处建议使用弗罗林。Have you tried Postgres' non-standard
UPDATE .. FROM
clause? I imagine, this would workNote that I'm forcing
genid()
to be called exactly once per record inmytable
within the subselect. Then I'm self-joiningmytable
andgen
using a hypotheticalid
column.See the documentation here:
http://www.postgresql.org/docs/current/interactive/sql-update.html
This seems to have been introduced with Postgres 9.0 only, though.If that seems too complicated (i.e. not very readable), you can still resort to pgplsql as user Florin suggested here.我建议使用以下 -
I would suggest to use following -
你能检查一下这在 postgres 中是否有效吗?
更新:
只是为了这个想法:你能用光标尝试一下吗?
Can you check if this is working in postgres?
Update:
just for the ideea: Can you try it with a cursor?