postgres in运算符引发错误:数组“”变量处或附近出现语法错误

lp0sw83n  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(343)

我在制造 function 我的一个特点是使用sql IN 接线员。基本上我想这样问

select name
from atlas_ins_th_travel_place pp
where pp.name IN ('Guyana', 'Mexico');

然后我做 function 并接受 varchar[] 作为这样的输入

CREATE OR REPLACE FUNCTION test_place(
    places VARCHAR[]
) RETURNS SETOF test_place_view AS
$$
DECLARE
    dummy ALIAS FOR $1;
BEGIN
--    FOR i IN 1 .. array_upper(places, 1)
--        LOOP
--           RAISE NOTICE '%', places[i];      -- single quotes!
--             array_append(dummy, places[i])
--        END LOOP;
    RETURN QUERY
    select name
    from atlas_ins_th_travel_place
    where name in places;
END;
$$ LANGUAGE plpgsql STABLE;

不幸的是,它引发了关于 operator . 我试过制作新的数组并使用它。但这没有帮助
问题:
如何使用 IN 操作员 array ?

hgc7kmma

hgc7kmma1#

你需要使用任何运算符。在使用列表时,任何数组都适用 select name from table where name = ANY(places)

mfuanj7w

mfuanj7w2#

操作员 IN 仅支持列表。它不支持在数组中搜索。你应该使用运算符 = ANY() .

postgres=# select 10 = ANY(ARRAY[10,20,30]);
┌──────────┐
│ ?column? │
╞══════════╡
│ t        │
└──────────┘
(1 row)

postgres=# select 11 = ANY(ARRAY[10,20,30]);
┌──────────┐
│ ?column? │
╞══════════╡
│ f        │
└──────────┘
(1 row)

或者你可以用一个函数 array_position (但不使用统计数据):

postgres=# select array_position(ARRAY[10,2,3], 10);
┌────────────────┐
│ array_position │
╞════════════════╡
│              1 │
└────────────────┘
(1 row)

postgres=# select array_position(ARRAY[10,2,3], 11);
┌────────────────┐
│ array_position │
╞════════════════╡
│              ∅ │
└────────────────┘
(1 row)

如果数组很小(<100),那么使用什么并不太重要。对于较大的数组,最好使用运算符。但这取决于上下文。

相关问题