PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

come selezionare solo valori univoci dalle tabelle correlate

È possibile utilizzare una funzione finestra per eseguire il join esterno solo sulle prime righe:

select t.id, t.b1_name, b2.b2_name
from (
  select p.id, b1.b1_name, row_number() over (partition by p.id order by b1_name) as rn
  from parent p
    join branch_1 b1 on b1.parent_id = p.id
) t
  left join (
    select parent_id, b2_name, 
           row_number() over (partition by parent_id) as rn
    from branch_2 
  ) b2 on b2.parent_id = t.id and b2.rn = t.rn
order by t.id;

Esempio online:https://rextester.com/GNYF31027