Question

I have a history table which I would like to use to find the latest user in which updated specific items. Here is the query I have so far:

SELECT * 
  FROM  `history` 
WHERE  `pKey` 
  IN ( 13309, 13311, 13951, 14244, 1500, 15558, 15691, 15938, 9769 ) 
ORDER BY  `history`.`time` DESC 
LIMIT 0 , 30

This returns multiple history results for each pkey. Is there a way to limit the results to only the latest (based on time) entry from the specific pkey?

So for example: Right now pkey 13309 has multiple results returned. The query should only return the latest result for it. Same goes for 13311... etc.

Was it helpful?

Solution

This should do:

SELECT h.*
FROM `history` as h
INNER JOIN (SELECT `pkey`, MAX(`time`) as MaxTime
            FROM `history`
            WHERE `pkey` IN (13309, 13311, 13951, 14244, 1500, 
                             15558, 15691, 15938, 9769)
            GROUP BY `pkey`) as t
    ON h.`pkey` = t.`pkey`
    AND h.`time` = t.`MaxTime`

OTHER TIPS

this should work. Just grouping all the rows that have the same pkey. I think this will work. Comment with a feedback.

Select * from (
SELECT * 
  FROM  `history` 
WHERE  `pKey`
  IN ( 13309, 13311, 13951, 14244, 1500, 15558, 15691, 15938, 9769 ) 
ORDER BY  `history`.`time` DESC) as t1 group by pKey
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top