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

193
Visualizações
SQL Join table from 1 of 2 different tables optimized search

As a simplification, I have four tables, book, publisher, author, and company. Both book and publisher have a reference to author, but that reference can be null.

I can find the author by joining the author table using an OR join query like this, but it is incredibly slow.

edit I have to use the author table to join another.

Schema:

schema design

select book.title, author.name, company.name as company_name from book inner join publisher on book.publisher_id = publisher.id inner join author on (book.author_id = author.id OR publisher.author_id = author.id) inner join company on author.company_id = company.id;

I am wondering what the best way to optimize this query would be, instead of joining on an OR conditional. Thanks

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

0

You are correct. OR in the ON clause can really slow down a query.

Instead, use two left joins:

select b.title, coalesce(ab.name, ap.name) as name
from book b inner join
     publisher p
     on b.publisher_id = p.id left join
     author ab
     on b.author_id = ab.id left join
     author ap
     on p.author_id = ap.id;

Formally, you might need to add where ab.id is not null or ap.id is not null if you only want to return rows with a match in one of the tables.

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