简体   繁体   中英

Get last record in mysql table

I have a database as such

  Update       Record_ID   Index    Location
    1          1             23       China
    1          1             24       Beijing
    1          1             45       Norway
    1          1             23       China
    2          1             423      Somne
    2          1             24       Beijing
    2          1             243      Nevela
    3          1             334      DEro
    3          1             555      Mood

I have tried other examples on this site which can't solve my situation yet so please don't be fast to tag this as a duplicate.

In this scenario i have only 1 record 1 but they could be thousands.

So i need to get the last record of Updates for all unique records. So in this case i should have something like this returned for record 1:

 3          1             334      DEro
 3          1             555      Mood

and if there is record 2 etc they will be included here as well.

I tried using "LIMIT" but my query returned only 1 row in this case.

3          1             555      Mood

PS: There is an autogenerated PK column for this table which i didnt include.

Online Demo .

  SELECT * FROM table t1 
JOIN (SELECT Record_ID  ,MAX(Updates)as maxupdate FROM table GROUP BY Record_ID)x 
ON t1.Record_ID = x.Record_ID  AND t1.Updates=x.maxupdate

Fiddle

It also works for multiple Record_id

Try This

SELECT * FROM Table_Name
WHERE `Update` = (SELECT TOP 1 `Update` FROM Table_Name ORDER BY ID DESC)

Try this. This is what I came up with... It works on SQLFiddle :) I got the results you want.

SELECT * 
FROM s 
WHERE updates=(SELECT MAX(updates) as Latest_Update
               FROM s
               GROUP BY record_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM