簡體   English   中英

Postgres為每行做數組agg

[英]Postgres do array agg for each row

我有一個查詢,將從我的醫生表中獲取jobs_locum_hospital_ids,然后將其與id上的醫院表連接並獲取名稱,然后將所有這些都放入一個數組中。

等等[187,123] -> ("George Eliot Hospital - Acute Services"),("Good Hope Hospital")

select array_agg(t)
        from (
        select h.name from (select jsonb_array_elements_text(d.jobs_locum_hospital_ids)::int as id  from doctor d
        where d.id = 11720) as q1
        left join hospital h on h.id = q1.id
                )t

但這僅where d.id = 11720情況下執行此where d.id = 11720 。我想對每一行執行此操作。 所以以某種方式加入

select * from doctor
left join that thing above

很難弄清您的數據結構或為什么要為此使用json函數。 據我所知,醫生有一系列的醫院ID,您需要這些名稱:

select d.*,
       (select array_agg(h.name)
        from unnest(d.jobs_locum_hospital_ids) dh join
             hospital h 
             on dh = h.id
       ) as hospital_names
from doctors;

只是,要做到這一點,事實表明,你真的想結合表, doctorHospitals每個醫生和醫院的每一個行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM