I have an activities table that has a foreign key reference to a users table. A user can have many activities, and I have a job that will populate their activities on a daily basis. After that job runs, I want to run a SQL query that will delete the oldest records per user and keep the latest 10. This is the schema:
users
id name
1 Jimmy
2 Johnny
user_activities
id user_id activity date
1 1 foo 2020-08-07 00:00:00
2 1 bar 2020-08-08 00:00:00
3 1 baz 2020-08-09 00:00:00
4 2 foo 2020-08-07 00:00:00
5 2 bar 2020-08-08 00:00:00
6 2 baz 2020-08-09 00:00:00
How can I write a query to truncate records up to the latest 10 for each user?
Best Answer
This works with mysql 5.x and abouve
mysql has since version the window function ROW_NUMBER so that the subquery can be written without user defined variables
I added some data to show that it works
The idea is simple, sort all dates by user_id and keep the 10 newest, the rownumber defines the position of the record sorted by date descending
db<>fiddle here
For Sql Server
3 rows affected
db<>fiddle here