Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to get the last entry for each foreign key of a history table?

I always wondered what the proper way would be to find the last entry in a history table of a certain foreign key?

Example:

We assume we have a table like this:

tHistory (ID | FK_User | State | Timestamp)

What would be the proper way in Oracle to read the lates entry for each FK_User ID? I always used a subselect for this, but it doesn't look right to me... any other ways to do this?

like image 358
nino Avatar asked Dec 28 '22 23:12

nino


1 Answers

An alternative could be to use a correlated sub-query to determine the last date...

SELECT
  *
FROM
  tHistory
WHERE
  timestamp = (
    SELECT
      MAX(timestamp)
    FROM
      tHistory latest
    WHERE
      FK_User = tHistory.FK_User
  )
like image 121
MatBailie Avatar answered Mar 30 '23 00:03

MatBailie