简体   繁体   中英

Get list of last record for each ID in SQL

I would like to get last records by every id_foreign in sql, example what I want to do:

input:

id: 1, id_foreign: 5, value: 1 
id: 2, id_foreign: 4, value: 2 
id: 3, id_foreign: 4, value: 3 
id: 4, id_foreign: 5, value: 4 
id: 5, id_foreign: 5, value: 5 

output:

id: 3, id_foreign: 4, value: 3 
id: 5, id_foreign: 5, value: 5

What about DISTINCT ? Any other idea? Understand me?

tried this solution:

SELECT * FROM table 
GROUP BY id_foreign 
ORDER BY id DESC

but outputs me:

id: 1, id_foreign: 5, value: 1 
id: 2, id_foreign: 4, value: 2 

I tried both (ASC and DESC) and bad output too.

A simple but not necessarily the most optimal way of querying this is using NOT EXISTS :

SELECT *
FROM MyTable t
WHERE NOT EXISTS (
    SELECT * FROM MyTable tt WHERE tt.id_foreign=t.id_foreign AND tt.id > t.id
)

Demo on SqlFiddle.

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