【发布时间】:2021-10-28 08:08:26
【问题描述】:
鉴于此表设置:
create table accounts (
id char(4) primary key,
first_name varchar not null
);
create table roles (
account_id char(4) references accounts not null,
role_type varchar not null,
role varchar not null,
primary key (account_id, role_type)
);
和初始帐户插入:
insert into accounts (id, first_name) values ('abcd', 'Bob');
我想获取某人的所有帐户信息,以及他们作为键值对所拥有的角色。对这种一对多关系使用连接会在包含角色的每一行中复制帐户信息,因此我想创建一个 JSON 对象。使用这个查询:
select
first_name,
coalesce(
(select jsonb_build_object(role_type, role) from roles where account_id = id),
'{}'::jsonb
) as roles
from accounts where id = 'abcd';
我得到了这个预期的结果:
first_name | roles
------------+-------
Bob | {}
(1 row)
添加第一个角色后:
insert into roles (account_id, role_type, role) values ('abcd', 'my_role_type', 'my_role');
我得到另一个预期结果:
first_name | roles
------------+-----------------------------
Bob | {"my_role_type": "my_role"}
(1 row)
但添加第二个角色后:
insert into roles (account_id, role_type, role) values ('abcd', 'my_other_role_type', 'my_other_role');
我明白了:
ERROR: more than one row returned by a subquery used as an expression
如何用
替换此错误 first_name | roles
------------+-----------------------------
Bob | {"my_role_type": "my_role", "my_other_role_type": "my_other_role"}
(1 row)
?
我正在使用 Postgres v13。
【问题讨论】:
标签: sql json postgresql