【问题标题】:access and modify multidimensional arrays in postgres在 postgres 中访问和修改多维数组
【发布时间】:2017-11-15 18:27:22
【问题描述】:

我不知道如何在 postgres 中更改多维数组。假设有以下代码:

do
$$
declare 
    a double precision[][];
    x integer;
    y integer;

begin
    for x in 1..3 loop
        for y in 1..3 loop
            a[x y]:= x * y;
            raise notice 'x: %, y: %, value: %, should be: %',x, y,   a[x:y], x*y;
        end loop;
    end loop;
end 
$$
language plpgsql;

结果如下:

x: 1, y: 1, value: {1}, should be: 1
x: 1, y: 2, value: {2}, should be: 2
x: 1, y: 3, value: {3}, should be: 3
x: 2, y: 1, value: {}, should be: 2
x: 2, y: 2, value: {4}, should be: 4
x: 2, y: 3, value: {6}, should be: 6
x: 3, y: 1, value: {}, should be: 3
x: 3, y: 2, value: {}, should be: 6
x: 3, y: 3, value: {9}, should be: 9

如您所见,存在一些问题。例如x=2y=1 的组合结果为{}

通常我会认为我可以通过

a[x][y]:= value;

但这会产生错误。

【问题讨论】:

    标签: sql arrays postgresql multidimensional-array plpgsql


    【解决方案1】:

    您的示例操作一维数组 - 您可以使用 array_ndims(a) 检查它。或者只是raise info '%',a;

    改为尝试a[x][y]:= value; 方法,明确定义尺寸以避免错误,例如:

    do
    $$
    declare
        a double precision[][];
        x integer;
        y integer;
    
    begin
        a := array[[NULL,NULL,NULL],[NULL,NULL,NULL],[NULL,NULL,NULL]];
        for x in 1..3 loop
            for y in 1..3 loop
                a[x][y]:= x * y;
                raise notice 'x: %, y: %, value: %, should be: %',x, y,   a[x][y], x*y;
            end loop;
        end loop;
        raise info '%',a;
    end
    $$
    language plpgsql;
    NOTICE:  x: 1, y: 1, value: 1, should be: 1
    NOTICE:  x: 1, y: 2, value: 2, should be: 2
    NOTICE:  x: 1, y: 3, value: 3, should be: 3
    NOTICE:  x: 2, y: 1, value: 2, should be: 2
    NOTICE:  x: 2, y: 2, value: 4, should be: 4
    NOTICE:  x: 2, y: 3, value: 6, should be: 6
    NOTICE:  x: 3, y: 1, value: 3, should be: 3
    NOTICE:  x: 3, y: 2, value: 6, should be: 6
    NOTICE:  x: 3, y: 3, value: 9, should be: 9
    INFO:  {{1,2,3},{2,4,6},{3,6,9}}
    DO
    

    另外请注意 - 我将冒号切片更改为 raise 中的精确索引

    【讨论】:

    • 谢谢。这很有帮助。
    • 我很高兴 - 很高兴它有帮助
    • 初始化部分可以使用函数array_fill:array_fill(null::double precision, array[3,3]);
    • 感谢您的通知。我完全同意,它会更整洁,但 OP 不会看到 [[],[]] 构造。我认为这样更容易理解——整个 OP 是关于不理解多维数组,所以我试图“展示”它们
    猜你喜欢
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多