【问题标题】:Postgres: How to return an integer array from stored functionPostgres:如何从存储函数返回一个整数数组
【发布时间】:2014-11-10 21:42:21
【问题描述】:

我想使用以下内容创建查询:

select id, array(id_adj(id)) from existingtable

这将是两列:第一列带有 id,第二列带有整数数组。

函数id_adj返回一组行(单列整数),写法如下:

DROP FUNCTION IF EXISTS id_adj(hz_id int);
CREATE FUNCTION id_adj(id int) returns SETOF int AS $$
    select b.id
        from existingtable a, existingtable b
        where a.id != b.id
          and a.id=$1
          and ST_Distance(a.wkb_geometry, b.wkb_geometry) <= 0.05
$$LANGUAGE SQL

上述函数适用于单个 id。例如:

select id_adj(462);

返回具有整数值的单列。

我知道 array() 函数在给定 SELECT 语句的查询结果的情况下返回一个值数组。例如:

select array(select id from existingtable where id<10);

返回一个数组“{6,5,8,9,7,3,4,1,2}”。

但是将两者结合在一起似乎不起作用。请注意,虽然我在上面使用了 postgis ST_Distance 函数,但不需要测试我的问题的解决方案。

我也愿意让函数返回一个数组而不是一组记录,但起初这似乎更复杂。

【问题讨论】:

    标签: arrays postgresql stored-procedures


    【解决方案1】:

    您缺少select 声明

    select
        id,
        array(select id_adj(id))
    from existingtable
    

    【讨论】:

    • 谢谢,很简单!
    猜你喜欢
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2021-06-14
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    相关资源
    最近更新 更多