I have a table like this:
key data created
1 a 14:15
2 b 14:16
2 c 14:17
1 a 14:18
3 b 14:19
3 c 14:20
3 a 14:21
1 b 14:22
2 c 14:23
2 c 14:24
I want to get the last 2 unique keys with the latest data inserted. in other word, i want a query that will get me: 1,2
but when I do something like this:
SELECT distinct(key) FROM logs ORDER BY created DESC LIMIT 0,1
or this:
SELECT key FROM logs GROUP BY key ORDER BY created DESC LIMIT 0,1
I only get: 2,3
probably because these are the last keys in the table.
I couldn’t figure out how to get the 2 keys with the latest data
Try this:
You did not select the maximum (that is the the latest creation time) per key.
So just use
GROUP BYto select perkeyand add aMAX( created )to select the last appearance for eachkey. Applying the respectiveORDER BYandLIMITclauses, you get the desired result.Example Fiddle