----------
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!
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With