将查询结果返回到数组中

时间:2010-06-23 23:34:42

标签: sql postgresql plr

以下代码段创建了三个数组,这些数组将传递给PL / R函数。

FOR s_id, s_latitude, s_longitude IN 
  SELECT
    s.id,
    s.latitude_decimal,
    s.longitude_decimal
  FROM
    climate.station s
  WHERE
    s.applicable AND
    s.latitude_decimal BETWEEN box.latitude_min AND box.latitude_max AND
    s.longitude_decimal BETWEEN box.longitude_min AND box.longitude_max
LOOP
  SELECT array_append( v_id, s_id ) INTO v_id;
  SELECT array_append( v_latitude, s_latitude ) INTO v_latitude;
  SELECT array_append( v_longitude, s_longitude ) INTO v_longitude;
END LOOP;

数组声明为:

  v_id integer[];
  v_latitude double precision[];
  v_longitude double precision[];

我宁愿使用CREATE TYPE并传递一个数组,每个元素包含三个值。

您如何对此进行编码,以便它不使用FOR ... LOOP

PL / R功能的第一行是:

stations <- cbind( v_id, v_longitude, v_latitude )

我想消除这行代码并简化SELECT查询。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码并继续使用3个数组:

SELECT
  array_agg(s.id),
  array_agg(s.latitude_decimal),
  array_agg(s.longitude_decimal)
INTO
  v_id, v_latitude, v_longitude
FROM
  climate.station s
WHERE
  s.applicable AND
  s.latitude_decimal BETWEEN box.latitude_min AND box.latitude_max AND
  s.longitude_decimal BETWEEN box.longitude_min AND box.longitude_max

或使用行构造函数并组装一个复合类型的数组:

SELECT
  array_agg((
    s.id,
    s.latitude_decimal,
    s.longitude_decimal
  ))
INTO
  v_id, v_latitude, v_longitude
FROM
  climate.station s
WHERE
  s.applicable AND
  s.latitude_decimal BETWEEN box.latitude_min AND box.latitude_max AND
  s.longitude_decimal BETWEEN box.longitude_min AND box.longitude_max
顺便说一下,这只适用于PostgreSQL 8.4 +

答案 1 :(得分:1)

根据pl/r documentation,“......二维PostgreSQL数组映射到R矩阵......”

也许像......

  SELECT
    plr_function(
      array_agg(array[s.id,s.latitude_decimal,s.longitude_decimal])
    )
  FROM
    climate.station s
  WHERE
    s.applicable AND
    s.latitude_decimal BETWEEN box.latitude_min AND box.latitude_max AND
    s.longitude_decimal BETWEEN box.longitude_min AND box.longitude_max