PostgreSQL:不使用函数,如何比较嵌套数组?

PostgreSQL: Without using a function, how can nested arrays be compared?

我在 Metabase 中使用 PostgreSQL(我有只读权限,所以函数无法运行)

我在两列中有以下嵌套数据:

Categories_A    Categories_B
{"A"}           {"B","F","C"}
{"B","A"}       {"Z","B","F"}
{"B","F"}       {"A","E","R"}

我想 return 在新的专栏中 categories_B 中缺失的 category/categories 与 categories_A 相比 - Categories_A 中的内容是不在 categories_B。所以理想情况下:

Categories_A    Categories_B      Missing_Category
{"A"}           {"B","F","C"}     {"A"}
{"B","A"}       {"Z","B","F"}     {"A"}
{"B","F"}       {"A","E","R"}     {"B","F"}

这是我的代码,但由于我在 Metabase 中的“只读”权限,它不起作用。

create function array_except(p_one anyarray, p_two anyarray)
  returns anyarray
as
$$
  select array_agg(e)
  from (
    select e
    from unnest(p_one)
    except
    select e
    from unnest(p_two)
  )
$$
language plpgsql
immutable
;

select categories_a, categories_b, 
       array_except(categories_a, categories_b) as missing_categories
from my_table

没有函数怎么实现?

由于 PostgreSQL 中没有 array_except 函数或运算符,您必须在查询中解压数组:

SELECT id,
       CASE missing_categories
            WHEN ARRAY[NULL]::text[]
            THEN ARRAY[]::text[]
            ELSE missing_categories
       END
FROM (SELECT tab.id,
             array_agg(arr.elem) AS missing_categories
      FROM tab
         LEFT JOIN LATERAL unnest(tab.categories_a) AS arr(elem)
            ON NOT tab.categories_b @> arr.elem
      GROUP BY tab.id) AS q;

外部查询仅用空数组替换由于外部连接而出现的 NULL 元素的数组。