【问题标题】:INSERT rows from multi-dimensional array in Postgres从 Postgres 中的多维数组中插入行
【发布时间】:2021-09-17 03:06:57
【问题描述】:

我有下表:

CREATE TABLE "public"."users" (
    "roles" _text CHECK ((array_ndims(roles) = 2) AND (array_length(roles, 2) = 3)),
    "userId" varchar(1000) NOT NULL
);

产生以下结果:

userId     | roles
------------------
foobarbaz  | {{user,owner,123},{organization,owner,456}}

我有一个单独的表,其架构如下:

CREATE TABLE "public"."roles" (
    "domain" varchar(1000) NOT NULL,
    "role" varchar(1000) NOT NULL,
    "domainId" varchar(1000) NOT NULL,
    "userId" varchar(1000) NOT NULL,
);

我正在尝试编写一个查询,该查询从用户表中获取行并填充角色表

所以角色表中的结果将是:

userId     | domain       | role  | domainId
-------------------------------------------
foobarbaz  | user         | owner | 123
foobarbaz  | organization | owner | 456

我正在考虑使用unnest() 函数,但这会将用户角色列拆分为多行。使用selectinsert 的组合,我最好的选择是什么?

【问题讨论】:

  • 是的,多维数组在 postgresql 中没有得到很好的支持,unnest 只会给你一层未嵌套的数据。您可能必须使用 UDF 将其作为字符串处理,因为使用 array_ndims 的传递可能会有所帮助

标签: sql postgresql database-design


【解决方案1】:

再想一想,既然你有这个CHECK ((array_ndims(roles) = 2) AND (array_length(roles, 2) = 3)),你总是有ARRAY [2,3]。

这不是最干净的,但如果它只是一次性的,它会特别有效:

insert into public.roles (userid,domain, role, domainid) 
select  "userId", roles[1][1] "domain" , roles[1][2] "role" ,roles[1][3] domainid
from users 
union all
select  userId, roles[2][1] , roles[2][2],roles[2][3]   
from users ;

【讨论】:

    猜你喜欢
    • 2017-06-14
    • 2011-05-26
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多