简体   繁体   中英

Get all data for an entity from another table in one query

I have this query

select * 
from (
  select c.*,p.name as project_name,u.firstname || ' ' || u.lastname as fullname, u.email as owner_email, u.payment_method, u as user, u.id as user_id, u.api_id, u.api_key,
         v.name as vendor_name, v.exid as vendor_id, s.number as sim_number, vm.exid as vendor_model_id, vm.name as vendor_model_name, cr.status as is_recording, 
         cr.storage_duration as cloud_recording_storage_duration, cr.schedule as schedule, cr.frequency as frequency,
         (select count(id) as total from camera_shares cs where c.id=cs.camera_id) as total_share 
  from cameras c
    inner JOIN users u on c.owner_id = u.id
    left JOIN projects p on c.project_id = p.id
    left JOIN sims s on c.id = s.camera_id
    left JOIN vendor_models vm on c.model_id = vm.id
    left JOIN vendors v on vm.vendor_id = v.id
    left JOIN cloud_recordings cr on c.id = cr.camera_id
) c

this gives me all cameras and with all relevant values which I require.

now there is another table, snapshot_extractors and it has a relation with the camera on id and camera_id in extractors table, as one camera can have more than 1 extractors.

在此处输入图像描述

In the above query, I want to get all extraction for one camera, I can do it in a separate query, but is it possible to get all extractions in the above query as an array of all extractions for a camera?

You can use another correlated subquery:

(select array_agg(e.extraction)
 from snapshot_extractors e
 where e.camera_id = c.camera_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