PostgreSQL选择复合元素的数组

时间:2011-07-28 19:15:28

标签: arrays postgresql composite

我在复合类型上定义了一个表:

create type footype as (  
a double precision,
b double precision
);  

create table footable as (  
x integer,  
y footype []);

如何在表中包含的复合元素的单个字段上使用select语句?

提前致谢,
安东尼奥

3 个答案:

答案 0 :(得分:8)

通常array access syntax后跟通常的composite type access syntax。所以为演示目的进行了一些设置:

=> insert into footable (x, y) values(1, ARRAY[(1.0,2.0)::footype]);
=> select * from footable;
 x |     y     
---+-----------
 1 | {"(1,2)"}
(1 row)

然后:

=> select y[1].a, y[1].b from footable where x = 1;
 a | b 
---+---
 1 | 2
(1 row)

您还可以在WHERE子句中访问复合类型:

=> select * from footable where y[1].b < 3;
 x |         y         
---+-------------------
 1 | {"(1,2)"}
(1 row)

答案 1 :(得分:5)

首先,有一个错误,创建表查询中的'as'一词是错误的。你应该写这个:

create table footable (
    x integer,  
    y footype []
);

将数据插入表中:

insert into footable(x, y) values(10, ARRAY[ ROW(1.0,2.0), ROW(3,4)]::footype[] );

# select * from footable;
 x  |         y         
----+-------------------
 10 | {"(1,2)","(3,4)"}
(1 row)

按字段获取数据:

# select x, y[1], y[1].a, y[1].b from footable;

 x  |   y   | a | b 
----+-------+---+---
 10 | (1,2) | 1 | 2
(1 row)

答案 2 :(得分:0)

我已经更正了无效的解决方案,因为它在generate_subscripts()函数中有错误。我已更改此函数中的列,因为它必须是数组类型列(y),而不是原子(x):

=> select * from (select x, y, generate_subscripts(y,1) as s from footable) as coord where y[s].a = 2.5;