2017-07-29 140 views
2

如果數組等於另一個可視爲數組數組的多維數組的元素,那麼我想使用過濾查詢來檢查它。如何檢查數組是否在多維數組

例如:

鑑於多維數組{{1,2}, {3,4}, {5,6}}我要檢查,如果該數組的元素中的一個的一維數組。

預期的結果:

  • 輸入:{1,2}{3,4} - >輸出:TRUE
  • 輸入:{2,3}{1,5} - >輸出:FALSE

我已經嘗試過<@,但它將返回所有示例情況下的TRUE,並且不能使用ANY而不切分multidi維數組。

有沒有人有沒有使用解決方案pgplsql

+0

可以ypu什麼侯試過了? –

回答

1

這似乎是一個難以解決的問題,沒有任何pgpsql。但是,如果使用了該功能時,它是非常簡單的: https://wiki.postgresql.org/wiki/Unnest_multidimensional_array

CREATE OR REPLACE FUNCTION public.reduce_dim(anyarray) 
RETURNS SETOF anyarray AS 
$function$ 
DECLARE 
    s $1%TYPE; 
BEGIN 
    FOREACH s SLICE 1 IN ARRAY $1 LOOP 
     RETURN NEXT s; 
    END LOOP; 
    RETURN; 
END; 
$function$ 
LANGUAGE plpgsql IMMUTABLE; 

要使用:

create table array_test (arr integer[][]); 
insert into array_test (select '{{1,2}, {3,4}, {5,6}}'); 

select (case when '{1,2}' in (select reduce_dim(arr) from array_test) then true 
     else false end); 
case 
------ 
t 
(1 row) 

select (case when '{1,4}' in (select reduce_dim(arr) from array_test) then true 
     else false end); 
case 
------ 
f 
(1 row) 
1

簡單的辦法:在陣列搜索像字符串:

select '{{1, 2}, {3, 4}, {5, 6}}'::int[][]::text like '%{1,2}%'; 

情結方式:將數組分解爲片(不含plpgsql):

with t(x) as (values('{{1, 2}, {3, 4}, {5, 6}}'::int[][])) 
select * 
from t 
where (
    select bool_or(x[s:s] = '{{1,3}}') from generate_subscripts(x,1) as s);