2017-05-12 1 views
2

SQL 배열 인덱싱의 용도와 인덱싱 []의 반환 유형에 대해 완전히 혼동스러워합니다. postgres에서 int [] []에서 행을 추출하는 방법

는 I가 3,2 배열 가지고

select ARRAY[ 
    [1,1], 
    [2,2], 
    [3,3]]; 

--> {{1,1},{2,2},{3,3}} 

(BTW, pgadmin3이는 "배열 정수 []"말한다이 아닌 "배열 정수 [] []").

은 (인덱스 바로 1에서 시작?)의 내가 첫 번째 행을 추출 할 가정 해 봅시다 :

-- A 
select (ARRAY[ 
    [1,1], 
    [2,2], 
    [3,3]])[1]; 
--> NULL 

허을? 왜 {1,1} (int[] 유형)입니까?

-- B 
select (ARRAY[ 
    [1,1], 
    [2,2], 
    [3,3]])[1][:]; 

--> {{1,1}} 

...가 합법적 인 것 같습니다. 하지만 :

-- C 
select (ARRAY[ 
    [1,1], 
    [2,2], 
    [3,3]])[1][:][1]; 
--> {} 

왜 A와 다른가요?

int [] [] (1d 배열)의 행을 int [] (1d 배열)로 추출하려면 어떻게해야합니까?

답변

2

[] [] INT에서 행을 추출하는 방법 중첩되지 요소의 집합으로 포스트 그레스

에서 [] (int)로 : 당신은이 게시물에서 자세한 정보를 찾을 수 있습니다

select array_agg(elem) 
from unnest(array[[1,1],[2,2],[3,3]]) elem; 

    array_agg 
--------------- 
{1,1,2,2,3,3} 
(1 row) 

:


두 번째 부분 배열을 얻고 싶은 경우에 How to get the dimensionality of an ARRAY column? :

with my_data(id, arr) as (
values 
(1, array[ 
    [1,1], 
    [2,2], 
    [3,3]]), 
(2, array[ 
    [1,1,11], 
    [2,2,22], 
    [3,3,33]]) 
) 

select array_agg(elem) 
from my_data, 
unnest(arr[2:2]) elem 
group by id; 

array_agg 
----------- 
{2,2} 
{2,2,22} 
(2 rows) 

주 1. [2:2]이라는 표기법은 두 번째 요소에서 두 번째 요소까지의 슬라이스를 의미하므로 두 번째 하위 배열을 가리 킵니다.

참고 2. 다차원 배열에는 차원이 일치하는 배열식이 있어야합니다.

KLIN의 답변에 더하여
+0

이 모든 행을 얻는다. 두 번째 줄을 원한다면? – user48956

+0

수정 된 답변보기 – klin

+0

'{{...}}'은 (는) 2 차원 배열입니다. 나는 1d 배열 (행)을 원한다. arr [1]은 NULL이 arr이 2d이고, 요소가 1d이기 때문에 차이가 있습니다. – user48956

1

및 사용 기능 (일부 수정하여) here 제공 :

-- drop operator if exists -> (anyarray, int); 
-- drop function if exists array_by_index(anyarray, int); 
-- drop function if exists reduce_dim(anyarray); 

create or replace function reduce_dim(anyarray) 
returns setof anyarray as 
$function$ 
declare 
    s $1%type; 
begin 
    if ($1 = '{}') or ($1 is null) then 
    return; 
    else 
    foreach s slice 1 in array $1 loop 
     return next s; 
    end loop; 
    return; 
    end if; 
end; 
$function$ 
language plpgsql immutable; 

create function array_by_index(anyarray, int) returns anyarray 
    language sql 
    immutable 
as $$ 
    select case when count(*) = 1 then reduce_dim($1[$2:$2]) else array_agg(x) end 
    from reduce_dim($1[$2:$2]) x 
$$; 

create operator -> (procedure = array_by_index, leftarg = anyarray, rightarg = int); 

select 
    array[[[1,1],[2,2]],[[3,3],[4,4]]]->2, 
    array[[1,2],[3,4],[5,6]]->3, 
    array[[1,2],[3,4],[5,6]]->3->1; 
╔═══════════════╤══════════╤══════════╗ 
║ ?column? │ ?column? │ ?column? ║ 
╠═══════════════╪══════════╪══════════╣ 
║ {{3,3},{4,4}} │ {5,6} │ {5}  ║ 
╚═══════════════╧══════════╧══════════╝ 
관련 문제