I have two tables: return, and return_details
Return is setup like so –
+ Return
- id
- orderNum
- startDate
- endDate
+ Return_Details
- id
- rid (Return.id)
- stage [this is essentially location]
- lastSeen [timeDate last seen)
I am attempting to find all returns that are “open” (where Return.endDate == null) and then the stage and lastSeen for each open Return.id.
The problem is I can’t figure out how to find the last occurrence of Return.id in Return_Details. Currently I am able to find the correct lastSeen time using MAX but how do I grab the corresponding stage.
Here’s the query I am using now –
SELECT r.so, rd.lastSeen, rd.stage, r.sotype, MAX(rd.lastSeen) as last
FROM repairs r
JOIN repair_details rd ON r.id = rd.rid
WHERE `enddate` IS NULL
GROUP BY r.so
ORDER BY lastSeen asc
Any assistance as to how this could be done with one query would be much appreciated. Thanks in advance!
This should work.
Edit 1:
This method will find the
MAX(id)for eachrid, then get the details based off thatMAX(id).SQL Fiddle