select
t1.id,
array_agg(
json_build_object('id', t2.id, 'status', t2.status)
) as statuses
from table1 t1
inner join table2 t2 on t1.id=t2.user_id
inner join table3 t3 on t1.id=t3.user_id
group by t1.id
table1
id , user
1 , 'A'
2 , 'B'
table2
user_id , status
1 , 'P'
1 , 'AP'
table3
user_id , something
1 , 'A12'
1 , 'B1212'
table3也是一对多的关系,结果是array_agg中的状态重复, 我尝试使用array_agg(distinct json_build_object())和array_agg(json_build_object()上的distinct), 在这种情况下,我们如何防止重复?
答案 0 :(得分:0)
只需将相关状态过滤为加入条件(1):
select
t1.id,
array_agg(
json_build_object('id', t2.id, 'status', t2.status)
) as statuses
from table1 t1
inner join table2 t2 on t1.id=t2.user_id
inner join table3 t3 on t1.id=t3.user_id
and t3.status = 'A12' -- 1.
group by t1.id
此外,如果要获取有效的JSON数组,则应使用json_agg()
而不是array_agg()
:
select
t1.id,
json_agg(
json_build_object('id', t2.id, 'status', t2.status)
) as statuses
from table1 t1
inner join table2 t2 on t1.id=t2.user_id
inner join table3 t3 on t1.id=t3.user_id
and t3.status = 'A12'
group by t1.id