Multiple Table Join

I have these four tables

Intermediate
      SOURCE_ID
      TARGET ID
      
Title
      ID
      Name
      
Author      
      ID
      Name
      

Publisher
      ID
      Name

Titles are related to Authors via the Intermediate table
Authors are related to Publishers via Intermediate
      
T.ID -> I.SOURCE_ID to I.TARGET_ID -> A.ID

A.ID -> I.SOURCE_ID to I.TARGET_ID -> P.ID

Given a Title name I need the Author and Publisher Name
It's pretty straight forward to join two tables via a common intermediate but I'm no sure of the join for this scenario.
Any ideas?
DaveChoiceTechAsked:
Who is Participating?
 
Shaun KlineLead Software EngineerCommented:
You would need to include the intermediate table in your query twice.
SELECT *
FROM Title T
INNER JOIN Intermediate TtoA ON T.ID = TtoA.Source_ID
INNER JOIN Author A ON TtoA.Target__ID = A.ID
INNER JOIN Intermediate AtoP ON A.ID = Atop.Source_ID
INNER JOIN Publisher P ON Atop.Target_ID = P.ID
WHERE T.Name = '<your title here>'

Open in new window

0
 
dsackerContract ERP Admin/ConsultantCommented:
Try this query:
SELECT  t.Name  AS TitleName,
        a.Name  AS AuthorName,
        p.Name  AS PublisherName
FROM    Title t
LEFT JOIN (SELECT a.Name,
                  i.SOURCE_ID AS Title_ID,
                  i.TARGET_ID AS Author_ID
           FROM   Author a
           INNER JOIN Intermediate i ON i.TARGET_ID = a.ID) a
    ON  a.Title_ID = t.ID
LEFT JOIN (SELECT p.Name,
                  i.SOURCE_ID AS Author_ID,
                  i.TARGET_ID AS Publisher_ID
           FROM   Publisher p
           INNER JOIN Intermediate i ON i.TARGET_ID = p.ID) p
    ON  p.Author_ID = a.Author_ID
WHERE t.Name = 'Title Name'

Open in new window

The assumption is that your Title.ID, Author.ID and Publisher.ID will not contain the same values, otherwise the Intermediate table could be clobbered with the same key values for the different sets of table relationships.

Also, I used LEFT JOINs so that you could see whether you actually had NO publisher at all.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.