TheCarver
TheCarver

Reputation: 19723

MySQL - Adding a JOIN to existing query

Having troubles adding a LEFT JOIN & INNER JOIN, combined, to an existing query.

I have two main tables; "photoSearch" containing all searchable data for my photos, and "photos", containing all data for my photos. I am using FULLTEXT across 3 fields in "photoSearch" to get relevant photoID's and then grabs the data from the "photos" table, like copyrights, sizes, dimensions...

This is my query:

SELECT p.photoID, p.setID, p.headline, p.caption, p.height, p.width, p.size, p.copyright
FROM photos AS p,
      (SELECT photoID FROM photoSearch WHERE MATCH (allPeople, allKeywords, shortCaption)
      AGAINST ('+byline' IN BOOLEAN MODE) LIMIT 0,50) AS photoIDs
WHERE p.photoID = photoIDs.photoID;

I now need to modify this query to include a LEFT JOIN and an INNER JOIN which gets any names of people shown in each photo, to print on-screen. Some photos do not have any people, hence needing a LEFT JOIN. I have this data across two tables (normalized); "photoPeople" and "people", so I came up with this join:

My Join (which needs adding to the above query)

LEFT JOIN ( photoPeople AS pp INNER JOIN people AS pe ON pp.peopleID = pe.PeopleID)
ON p.photoID = pp.photoID

But I'm finding it hard to fit it in my original query, as the sub-select query is in the comma delimited FROM list - it's confusing me. I also want to make sure that I'm not affecting the performance of the FULLTEXT index by joining where I shouldn't.

I did try adding it straight after the sub-select (before WHERE) but I was getting SQL errors saying it did not recognise column p.photoID.

Both original query and the DB design is not mine.

Any help or guidance would be gratefully received.

Upvotes: 1

Views: 287

Answers (2)

Zane Bien
Zane Bien

Reputation: 23125

SELECT 
    p.photoID, 
    p.setID, 
    p.headline, 
    p.caption, 
    p.height, 
    p.width, 
    p.size, 
    p.copyright,
    pe.*
FROM 
    photos p
INNER JOIN
    (
        SELECT photoID 
        FROM photoSearch 
        WHERE MATCH (allPeople, allKeywords, shortCaption) AGAINST ('+byline' IN BOOLEAN MODE) 
        LIMIT 50
    ) pids ON p.photoID = pids.photoID
LEFT JOIN
    photoPeople pp ON p.photoID = pp.photoID
LEFT JOIN
    people pe ON pp.peopleID = pe.peopleID

I don't see a need to INNER JOIN the people table on the LEFT JOIN because if the LEFT JOIN is NULL, the people will also be NULL

Upvotes: 4

sel
sel

Reputation: 4957

LEFT JOIN 
  ( SELECT pp.photoID,name FROM photoPeople AS pp INNER JOIN people AS pe 
    ON pp.peopleID = pe.PeopleID) aa
ON p.photoID = aa.photoID

Upvotes: 0

Related Questions