How to select last 5 results from each user_id in an sqlite database?
问题 I have a database with "num" table like this user_id | number | unix_time ----------------------------- 123 2 xxxxxxxx 123 40 xxxxxxxx 123 24 xxxxxxxx 333 23 xxxxxxxx 333 67 xxxxxxxx 854 90 xxxxxxxx I'd like to select the last 5 numbers inserted by each user_id, but I can't figure out how to do it. I tried: SELECT b.n, a.user_id FROM num a JOIN num b on a.user_id = b.user_id WHERE ( SELECT COUNT(*) FROM num b2 WHERE b2.n <= b.n AND b2.user_id = b.user_id ) <= 5 回答1: I am adapting the answer