Search code examples
mysqldatabaserdbms

MySQL group by with max value


Hi I have this table.

id  lat     lng     userId
1   12      23      1
2   45      34      2
3   42      34      3
4   33      34      1
5   36      79      2
6   53      98      2
7   23      90      3
8   23      67      1

Here we have three users. (user ids 1,2,3). I want to get lateset record (id column max value) of each user. My excepted output is this

userId  lat     lng
1       23      67
2       53      98
3       23      90

This query will give me group by option

SELECT 
    *
FROM
    covid.locations
GROUP BY userId;

But how do I combine this with MAX(id) function.


Solution

  • This will do

    SELECT
    *
    FROM
    covid.locations
    where id in (select max(t.id) from covid.locations t group by t.userId)
    order by id desc;
    

    An example of the above query can be found in this SQLFiddle