来自psql的数组错误:数组值必须以“}”或维度信息开头

时间:2019-12-05 12:16:53

标签: sql arrays postgresql plpgsql sql-function

我有三个表:

  1. 文本:行文本

  2. trigram:所有文字行的trigram

  3. text_trigram:文本行包含的三元组,中间表

我尝试执行此操作:

create or replace function get_values(IN t_id integer[], IN tri_id integer[], OUT count_values integer[][])
as $$
declare 
    count_value integer[];
    rec integer;
    tri_n integer := array_length(tri_id, 1);
begin 
    for rec in select unnest(tri_id)
    loop
        select into count_value count(text_id) from unnest(t_id) as required_t_id(r_t_id) left join text_trigram on text_id = required_t_id.r_t_id and trigram_id = rec group by text_id;
        count_values := array_cat(count_values, count_value);
    end loop;
end; $$
language plpgsql;

执行完此命令后,执行正常:

select * from get_values(ARRAY[9,210,999], ARRAY[621, 3266]);

错误消息出来了

  

数组错误:数组值必须以“}”或维度信息开头

我也在下面尝试过

select * from get_values('{9,210,999}','{621,3266}');

我收到一条错误消息:

  

函数get_values(未知,未知)

1 个答案:

答案 0 :(得分:1)

您正试图将查询返回的多行存储为单个整数(count(text_id)的结果)到数组(count_value)中-这将不起作用。

您需要将值聚合到单个数组中,然后将结果放入变量中,因为分组依据是,因此需要包装查询。

select array_agg(cnt)
  into count_value 
from (
  select count(text_id) as cnt
  from unnest(tri_id) as required_t_id(r_t_id) 
     left join text_trigram on text_id = required_t_id.r_t_id and trigram_id = rec 
  group by text_id
) t;

group by看起来非常奇怪,我想知道您是否真的是这样:

select count(text_id)
  into count_value 
from unnest(tri_id) as required_t_id(r_t_id) 
  left join text_trigram on text_id = required_t_id.r_t_id and trigram_id = rec;

您也不需要取消嵌套要循环的数组。

您的循环应如下所示:

foreach rec IN ARRAY t_id
loop
...
end loop;