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

452
Visualizações
Postgres how can I select just one row from a One -to-Many relationship between keys

I have the following query

SELECT dfile.id
FROM dcmstudy_t dstud
INNER JOIN dcmseries_t dser ON dstud.id = dser.dcmstudy_id
INNER JOIN dcmfile_t dfile ON dser.id = dfile.dcmseries_id
INNER JOIN finst_t fi ON dfile.id = fi.file_id
INNER JOIN store s ON s.id = fi.store_id
WHERE dser.id in (69823713)

when given the ID number in the WHERE clause, this query will return ~300 rows of dfile.id. The problem I have is I just need one dfile.id for each dser.id in the WHERE clause. I know if I was just providing one dser.id then I could just LIMIT 1, but I need to provide many dser.id in the WHERE clause and have each produce just one dfile.id. In the end I want to be able to produce a table that contains many different dser.id with each corresponding to one dfile.id. It is probably good to mention the relationship between dser.id and dfile.id is one to many, many dfile.id to one single dser.id. Any suggestions?

UPDATE

After looking over all your suggestions I came up with the following query that solved my problem.

SELECT dser.id,s.oname,Min(dfile.id) as FileID
FROM dcmstudy_t dstud
INNER JOIN dcmseries_t dser ON dstud.id = dser.dcmstudy_id
INNER JOIN dcmfile_t dfile ON dser.id = dfile.dcmseries_id
INNER JOIN finst_t fi ON dfile.id = fi.file_id
INNER JOIN store s ON s.id = fi.store_id
WHERE dser.id in (69823713,69644830,63763440)
group by dser.id,s.oname

Thanks everyone for the input.

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

0

Considering that the query mentioned in the question is correct, You can use distinct on clause of PostgreSQL as mentioned below:

Try this :

SELECT distinct on (dser.id)  dfile.id 
FROM dcmstudy_t dstud
INNER JOIN dcmseries_t dser ON dstud.id = dser.dcmstudy_id
INNER JOIN dcmfile_t dfile ON dser.id = dfile.dcmseries_id
INNER JOIN finst_t fi ON dfile.id = fi.file_id
INNER JOIN store s ON s.id = fi.store_id
WHERE dser.id in (69823713) 
order by dser.id, dfile.id

above query will return the first dfile.id.

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