简体   繁体   中英

postgresql - join into a property of json

I have two tables user and photo

When I select a few photo we can just do this

SELECT (
photos.id as photo_id, 
photo.url as photo_url,
user.id as user_id,
user.name as user_name)
FROM photo INNER JOIN user ON photo.user_id = user.id

and it would give this array of photos in this json format

[{
  photo_id,
  photo_url,
  user_id,
  user_name
}]

However, I would like something like this

[{
  id,
  url,
  user:{
    id,
    name
  }
}]

This structure can help allow me to access the array with a photos variable and iterating over the photos would be more intuitive.

Okay, so I did a bit of reading and found this to be a viable solution for now

select 
photo.id, photo.url,
(
    select row_to_json(u) from (
        select id, name from user where user.id = photo.user_id
    ) u
) as user
from photo;

Below query will produce the array of photos in the desired json format.

with users(id,name) as (
    select 1,'user1'::text
), photo(id,user_id,url) as (
    select 100,1,'http://photo.com/user1'::text
)
select
 json_agg(
     json_build_object(
         'id',p.id,
         'url',p.url,
        'user',row_to_json(u) 
     )    
 )    
from users u
join photo p on p.user_id=u.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM