0
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(distinct on json_build_object()),在这种情况下我们如何防止重复?

4

1 回答 1

1

只需过滤掉相关状态作为连接条件(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
于 2019-10-17T07:39:32.820 回答