Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
postgresql display two sublists in one result

Assuming the very simple schema

table main

main_id, ...
1      , ...
2      , ...

table sub1

main_id, sub1_data
1      , a
1      , b
2      , g

table sub2

main_id, sub2_data
1      , 1
2      , 1
2      , 2

As output I would like

main_id, sub1_data, sub2_data
1      , a        , 1
1      , b        , <null>
2      , g        , 1
2      , <null>   , 2

Using a union I can get close but then each list get's it's own rows

SELECT main_id, sub1_data, NULL
FROM sub1
UNION 
SELECT main_id, NULL, sub2_data
FROM sub2

result

main_id, sub1_data, sub2_data
1      , a        , <null>
1      , b        , <null>
1      , <null>   , 1
2      , g        , <null>
2      , <null>   , 1
2      , <null>   , 2

So is there a way to get them two share rows and just use as many rows as the longest list?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

One thing which can give you this "interleaved" output is the unnest() function with multiple parameters (or its equivalent: the ROWS FROM(...) construct):

Table functions may also be combined using the ROWS FROM syntax, with the results returned in parallel columns; the number of result rows in this case is that of the largest function result, with smaller results padded with null values to match.
...
The special table function UNNEST may be called with any number of array parameters, and it returns a corresponding number of columns, as if UNNEST had been called on each parameter separately and combined using the ROWS FROM construct.

select     main_id, sub1_data, sub2_data
from       (select main_id, array_agg(sub1_data) sub1_arr from sub1 group by main_id) s1
full join  (select main_id, array_agg(sub2_data) sub2_arr from sub2 group by main_id) s2 using (main_id)
cross join unnest(sub1_arr, sub2_arr) u(sub1_data, sub2_data)

http://rextester.com/QSWESJ84203

Note: this is a "relatively" new feature: it was introduced in 9.4

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda