将 JSONB_ARRAY_ELEMENTS 结果分配给 VARCHAR 数组

Assigning JSONB_ARRAY_ELEMENTS results to a VARCHAR array

当尝试分配 JSONB_ARRAY_ELEMENTS call to a VARCHAR array 的结果时(供以后在 SELECT ... WHERE IN (UNNEST(...)) 语句中使用),以下存储函数:

CREATE OR REPLACE FUNCTION test1(
        IN in_sids jsonb,
        OUT out_uid integer)
        RETURNS integer AS
$func$
DECLARE
        sids varchar[];
        uids integer[];
BEGIN
        sids := (SELECT x->>'sid' FROM JSONB_ARRAY_ELEMENTS(in_sids) x);
        -- uids := (SELECT uid FROM social WHERE sid IN (UNNEST(sids)));

        RAISE NOTICE 'sids = %', sids;
        RAISE NOTICE 'uids = %', uids;

        SELECT 1;
END
$func$ LANGUAGE plpgsql;

不幸地打印出错误:

# select test1('[{"sid":"aaa"},{"sid":"bbb"}]'::jsonb);

ERROR:  more than one row returned by a subquery used as an expression
CONTEXT:  SQL statement "SELECT (SELECT x->>'sid' FROM JSONB_ARRAY_ELEMENTS(in_sids) x)"
PL/pgSQL function test1(jsonb) line 6 at assignment

所以我尝试使用 ARRAY_AGG -

来修复作业
sids := SELECT ARRAY_AGG(SELECT x->>'sid' FROM JSONB_ARRAY_ELEMENTS(in_sids) x);

但出现语法错误:

ERROR:  syntax error at or near "SELECT"
LINE 10:         sids := SELECT ARRAY_AGG(SELECT x->>'sid' FROM JSONB...
                         ^

如何将 JSONB_ARRAY_ELEMENTS 结果存储到数组中?

更新:

我听从了 Nick 的建议(谢谢),但现在卡在了下一步:

CREATE OR REPLACE FUNCTION test1(
        IN in_sids jsonb,
        OUT out_uid integer)
        RETURNS integer AS
$func$
DECLARE
        sids varchar[];
        uids integer[];
BEGIN
        sids := (SELECT ARRAY_AGG(x->>'sid') FROM JSONB_ARRAY_ELEMENTS(in_sids) x);
        uids := (SELECT uid FROM social WHERE sid IN (UNNEST(sids)));

        SELECT 1;
END
$func$ LANGUAGE plpgsql;

尝试在 SELECT ... WHERE IN ... 语句中使用数组时:

# select test1('[{"sid":"aaa"},{"sid":"bbb"}]'::jsonb);
ERROR:  argument of IN must not return a set
LINE 1: SELECT (SELECT uid FROM social WHERE sid IN (UNNEST(si...
                                              ^
QUERY:  SELECT (SELECT uid FROM social WHERE sid IN (UNNEST(sids)))
CONTEXT:  PL/pgSQL function test1(jsonb) line 7 at assignment

你很接近...

sids := (SELECT ARRAY_AGG(x->>'sid') FROM JSONB_ARRAY_ELEMENTS(in_sids) x);

为了使用expression IN (subquery)结构,你需要编写一个独立的SELECT语句:

uids := (SELECT ARRAY_AGG(uid) FROM social WHERE sid IN (SELECT UNNEST(sids)));

或者,您可以使用 ANY:

检查值是否在数组中
uids := (SELECT ARRAY_AGG(uid) FROM social WHERE sid = ANY(sids));

如果您不使用 sids 数组进行稍后的计算,您可以将它们组合成一个查询:

uids := (
  SELECT array_agg(uid)
  FROM social
  JOIN JSONB_ARRAY_ELEMENTS(in_sids) x ON
    sid = x->>'sid'
);