Eric
Eric

Reputation: 575

Last occurrence of foreign key in reference table mysql

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!

Upvotes: 0

Views: 327

Answers (1)

Kermit
Kermit

Reputation: 34062

This should work.

SELECT a.id, b.stage, b.lastSeen
FROM Return a 
LEFT JOIN (SELECT rid, stage, MAX(lastSeen) AS lastSeen FROM Return_Details GROUP BY rid, stage) b ON b.rid = a.id
WHERE a.endDate IS NULL

Edit 1:

This method will find the MAX(id) for each rid, then get the details based off that MAX(id).

SELECT a.orderNum, c.stage, c.lastSeen
FROM repairs a 
LEFT JOIN 
  (SELECT rid, MAX(id) AS id FROM repair_details 
    GROUP BY rid) b ON b.rid = a.id
LEFT JOIN
  (SELECT id, stage, lastSeen FROM repair_details) c ON c.id = b.id
WHERE a.endDate IS NULL

SQL Fiddle

Upvotes: 2

Related Questions