【问题标题】:Array error from psql: Array value must begin with "}" or dimension information来自 psql 的数组错误:数组值必须以“}”或维度信息开头
【发布时间】:2020-03-30 08:59:40
【问题描述】:

我有三张桌子:

  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}');

我收到一条错误消息:

function get_values(unkonwn, unknown) 不清楚

【问题讨论】:

  • 你为什么要取消嵌套输入数组tri_id 两次?
  • @a_horse_with_no_name 抱歉,打错了,应该是t_id,我已经修改了
  • 认为整个循环可能是完全没有必要的,这可以通过单个聚合来完成,而无需 PL/pgSQL 开始 - 但无需解释 你想在那里做什么,这真的很难回答。
  • 你的肉我可以在选择而不是循环上做吗?我不确定,因为我这里需要的是一个二维数组
  • 嗯,SELECT 语句的结果本质上是一个二维“数组”

标签: sql arrays postgresql plpgsql sql-function


【解决方案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;

【讨论】:

  • @heisthere:您对数组的循环也不正确
  • 嘿,再次感谢。我的意思是你的解决方案是完全正确的。我会试试你的建议,它看起来更干净
  • 很难理解你真正想要实现的目标。请提出一个新问题,其中包括一些示例数据和基于该数据的预期输出为formatted text。请参阅 [此处]](meta.stackexchange.com/questions/81852),了解有关如何创建美观的文本表格的一些提示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 2016-03-13
  • 1970-01-01
相关资源
最近更新 更多