Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!