Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MAX condition on left outer join

Tags:

mysql

----------
samples
----------
SamplesID
stylenumber
stylename
status

-----------
samples_details
-----------
Samples_Details_ID
SamplesID
CustomerName
date_out
date_returned
updated (timestamp)
status

------------
samples_pictures
------------
SamplesPicID
SamplesID

Trying to write a query that gives me all rows from samples, all matches (if any) from samples_pictures, and the most recent record (if any) from samples_details. So two left outer joins, but one retrieving only the most recent record.

What's not working:

SELECT samples.*
     , samples_pictures.SamplesPicID
     , CustomerName
     , date_out
     , date_returned
     , updated
     , samples_details.status as txn_status 
FROM samples 
    LEFT OUTER JOIN
      ( SELECT Samples_Details_ID
             , samples_details.status as txn_status
             , MAX(updated) as MaxUpdated
        FROM samples_details
        GROUP BY Samples_Details_ID
      ) AS MaxTable
      ON MaxTable.SamplesID = samples.SamplesID 
    LEFT OUTER JOIN samples_pictures
      ON samples.SamplesID = samples_pictures.SamplesID

Any assistance would be greatly appreciated!

like image 785
TjJunior Avatar asked Oct 11 '22 07:10

TjJunior


2 Answers

Your original query still selects each record from samples_details.

You'll have to create a subselect to filter out only those records with the maximum timestamp and join this back with your samples_details table to get the additional columns.

SELECT   *
FROM     samples s
         LEFT OUTER JOIN sample_details sd ON sd.SamplesID = s.SamplesID
         INNER JOIN (
           SELECT   SamplesID
                    , MAX(update) AS Update
           FROM     samples_details
           GROUP BY
                    SamplesID
         ) sdm ON sdm.SamplesID = sd.SamplesID
         LEFT OUTER JOIN samples_pictures sp ON sp.SamplesID = s.SamplesID
like image 97
Lieven Keersmaekers Avatar answered Nov 02 '22 13:11

Lieven Keersmaekers


There's no SamplesID in your select statement for MaxTable. Should be:

SELECT samples.*, samples_pictures.SamplesPicID, CustomerName, date_out, 
date_returned, updated, samples_details.status as txn_status 
FROM samples 
    LEFT OUTER JOIN (SELECT SamplesID, Samples_Details_ID, samples_details.status as txn_status, 
    MAX(updated) as MaxUpdated FROM samples_details GROUP BY Samples_Details_ID) 
    AS MaxTable ON MaxTable.SamplesID = samples.SamplesID 
LEFT OUTER JOIN samples_pictures ON samples.SamplesID = samples_pictures.SamplesID
like image 31
dgilland Avatar answered Nov 02 '22 12:11

dgilland