如何分组,然后在提供的数组中获取带有ID的行

时间:2016-01-06 21:24:14

标签: postgresql

我的表结构:

table_A_id bigint,
group_id bigint,
sub_id bigint

我有一个bigint的外部2D数组。您可以将其视为一个可能的子ID列表,一个组必须匹配才能被选中。

例如,如果我的数据库中有10行(为了便于阅读而订购):

table_A_id | group_id | sub_id
---------------------------------
   1            1         1
   2            1         2
   3            1         3
   4            2         1
   5            2         2
   6            2         4
   7            2         5
   8            3         1
   9            3         5
   10           3         6

2d阵列是

[
   [1, 4],
   [1, 6]
]

然后将选择行4,6,8,10作为它们所在的组具有一组id,其中包含来自2d阵列中的一个阵列的所有项目。

Edit--
Rephrase as requested:
Grouping the rows by group_id gives
group 1 with sub_ids [1,2,3]
group 2 with sub_ids [1,2,4,5]
group 3 with sub_ids [1,5,6]
group 2 has both 1 & 4 within it's sub_ids, matching an array in the 2d array, therefore those rows are selected (4,6)
group 3 has both 1 & 6 within it's sub_ids, so those rows are also selected (8 & 10)
group 1 only has a matching sub_id of 1 and not also 4 or 6 so no rows from group 1 are selected

到目前为止,我正在努力使用1d阵列:

DEALLOCATE my_proc;
PREPARE my_proc (bigint[][]) AS
    SELECT *
    FROM (
        SELECT ufs.group_id, ufs.sub_id
        FROM table_A AS ufs
        GROUP BY ufs.group_id, ufs.sub_id
    ) AS ufs;
    --WHERE ufs.sub_id = ALL($1);

EXECUTE my_proc(array[array[1, 2], array[1,3]]);

1 个答案:

答案 0 :(得分:0)

这很简单,只需使用array_agg和包含运算符:

WITH table1
    ("table_A_id", "group_id", "sub_id")
AS(
    VALUES
      (1, 1, 1),
      (2, 1, 2),
      (3, 1, 3),
      (4, 2, 1),
      (5, 2, 2),
      (6, 2, 4),
      (7, 2, 5),
      (8, 3, 1),
      (9, 3, 5),
      (10, 3, 6)
),
seek(x) AS(
  VALUES 
    (array[1, 2]),
    (array[1,3])
)
SELECT group_id, array_agg(sub_id)
 FROM table1
 GROUP BY group_id
 HAVING array_agg(sub_id) @> ANY(SELECT x FROM seek)