使用Postgres 8.4中每行调用一次的函数进行更新

Cez*_*usz 6 sql database postgresql sql-update

我有以下UPDATE语句:

update mytable
   set a = first_part(genid()),
       b = second_part(genid()),
       c = third_path(genid())
 where package_id = 10;
Run Code Online (Sandbox Code Playgroud)

在这个例子中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;
Run Code Online (Sandbox Code Playgroud)

但它没有用,因为整个更新声明genid()只调用了一次.

Luk*_*der 8

你有没有尝试过Postgres的非标准UPDATE .. FROM条款?我想,这会奏效

update mytable
   set a = first_part(gen.id),
       b = second_part(gen.id),
       c = third_path(gen.id)
  from (
          select genid() as genid, id
          from mytable 
          where package_id = 10
       ) gen
 where mytable.id = gen.id;
 --and package_id = 10 -- This predicate is no longer necessary as the subquery
                       -- already filters on package_id, as Erwin mentioned
Run Code Online (Sandbox Code Playgroud)

请注意,我强制在subselect中为genid()每个记录调用一次mytable.然后我自我加入mytablegen使用一个假设的id专栏.请参阅此处的文档:

http://www.postgresql.org/docs/current/interactive/sql-update.html

但这似乎只是在Postgres 9.0中引入的.如果这看起来太复杂(即不太可读),你仍然可以使用pgplsql作为用户Florin在这里建议的.