检查组是否包含所提供的任何阵列中的所有ID

时间:2016-01-09 21:16:42

标签: arrays postgresql

我将2d数组传递给过程。该数组包含多个id数组。我想

  • 按group_id
  • 对表格进行分组 对于每个组,
  • 为2d数组中的每个数组
    • 如果此组具有此迭代数组中的所有ID,则将其返回

我在这里读到有关2d数组的问题:

postgres, contains-operator for multidimensional arrays performs flatten before comparing?

我想我差不多了,但我不确定如何解决这个问题。我理解为什么以下代码会产生错误"子查询只返回一列",但我无法解决如何解决它

DEALLOCATE my_proc;
PREPARE my_proc (bigint[][]) AS
WITH cte_arr AS (select $1 AS arr), 
     cte_s AS (select generate_subscripts(arr,1) AS subscript, 
     arr from cte_arr),
     grouped AS (SELECT ufs.user_id, array_agg(entity_id) 
    FROM table_A AS ufs
    GROUP BY ufs.user_id)
SELECT * 
FROM grouped
WHERE (select arr[subscript:subscript] @> array_agg AS sub,
    arr[subscript:subscript]
    from cte_s);
EXECUTE my_proc(array[array[1, 2], array[1,3]]);

1 个答案:

答案 0 :(得分:-1)

您可以为参数中的每个组和每个数组创建一行cross join

PREPARE stmt (bigint[][]) AS
    with    grouped as
            (
            select  user_id
            ,       array_agg(entity_id) as user_groups
            from    table_A
            group by
                    user_id
            )
    select  user_id
    ,       user_groups
    ,       $1[subscript:subscript] as matches
    from    grouped
    cross join
            generate_subscripts($1, 1) as gen(subscript)
    where   user_groups @> $1[subscript:subscript]
;

How to group by a Calculated Field