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

Array error from psql: Array value must begin with "}" or dimension information

我有三个 table:

  1. 文本:文本行

  2. 八卦:所有文本行的八卦

  3. text_trigram:一个文本行包含的八卦,中间table

我试着执行这个:

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]);

错误信息出来了

Array error: Array value must begin with "}" or dimension information

下面我也试过了,

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

我收到一条错误消息:

function get_values(unkonwn, unknown) is not clear

您正在尝试将查询返回的多行存储为一个整数(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;