0

我正在尝试使用复合键更新表,但无法弄清楚语法。我有一个表定义为:

create schema test;
create type test.ra_dec as (f1 double precision, f2 double precision);
create table test.pos_vel(
      xp double precision,
      yp double precision,
      xv double precision,
      yv double precision
);
insert into test.pos_vel(xp,yp,xv,yv) values
       (1,2,5,10),
       (2,3,10,20),
       (3,4,20,40);

我可以验证我的定义类型是否有效:

gsh=# select cast( (100,200) as test.ra_dec);
    row    
-----------
 (100,200)
(1 row)

但我不知道如何更新我的表。

gsh=# update test.pos_vel set (xv,yv) = (select cast( (100,200) as test.ra_dec));
ERROR:  syntax error at or near "select"
LINE 1: update test.pos_vel set (xv,yv) = (select cast( (100,200) as...

我知道对于这个简单的例子,我可以在不使用复合类型的情况下做到这一点,但出于速度原因,我想在 pl/python 中定义一个函数并让它返回一个复合类型,所以我需要找出正确的语法。

有人可以帮忙吗?

4

1 回答 1

1
-- drop schema if exists test cascade;
create schema test;
create type test.ra_dec as (f1 double precision, f2 double precision);

-- Your function here
create function test.f() returns test.ra_dec language sql as $$
  select (100,200)::test.ra_dec $$;

create table test.pos_vel(
      xp double precision,
      yp double precision,
      xv double precision,
      yv double precision
);
insert into test.pos_vel(xp,yp,xv,yv) values
       (1,2,5,10),
       (2,3,10,20),
       (3,4,20,40);

update test.pos_vel set (xv,yv) = (select * from test.f());

更新:

因为这种情况的子选择是在 PostgreSQL 9.5 中引入的,所以它在早期版本中不起作用。有两种解决方法:

update test.pos_vel set (xv,yv) = ((test.f()).f1, (test.f()).f2);

update test.pos_vel set (xv,yv) = (t.f1, t.f2) from (select * from test.f()) t;

在 8.4 上测试:http ://dbfiddle.uk/?rdbms=postgres_8.4&fiddle=0a4927ed804b76442a69f8259cca1929

于 2017-05-02T18:16:29.393 回答