A
A
Arman2015-10-11 15:02:34
MySQL
Arman, 2015-10-11 15:02:34

How to quickly find the last entry in a table?

Hello!
There is a table with user files, you need to find the last entry of each user:

CREATE TABLE `files` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `userId` int(10) unsigned NOT NULL DEFAULT '0',
...
  `uploadAt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',

It turns out we need to group by userId, but how to make the record match the userId?
SELECT MAX(`uploadAt`), * FROM `files` GROUP BY `userId`

Or
SELECT * FROM `files` WHERE `uploadAt` = MAX(`uploadAt`) GROUP BY `userId`

Or
SELECT * FROM `files` AS a WHERE `uploadAt` = (SELECT MAX(`uploadAt`) FROM `files` AS b WHERE b.userId = a.userId) GROUP BY `userId`

The last request sends the server to sleep =(
Or something else?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2015-10-11
@Arik

SELECT `t2`.*
    FROM (
        SELECT `userId`, MAX(`uploadAt`) AS `uploadAt`
        FROM `files`
        GROUP BY `userId`
    ) AS `t1`
    JOIN `files` AS `t2` USING (`userId`, `uploadAt`);

M
Mokhirjon Naimov, 2015-10-11
@zvermafia

Try this: sqlfiddle.com/#!9/a89e3/1/0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question