我有一个像这样的LoginTime表:
id | user_id | datetime
1 | 1 | 2011-01-19 18:51:01
2 | 1 | 2011-01-19 18:51:02
3 | 1 | 2011-01-19 18:51:03
4 | 1 | 2011-01-19 18:51:04
5 | 1 | 2011-01-19 18:51:05
6 | 1 | 2011-01-19 18:51:06
7 | 1 | 2011-01-19 18:51:07
8 | 1 | 2011-01-19 18:51:08
9 | 1 | 2011-01-19 18:51:09
10 | 2 | 2011-01-19 18:51:10
我想只保留5个最新的(按’datetime’列)记录,并删除user_id = 1的所有先前记录
是否有可能通过一个mySQL查询来实现这一点?
最佳答案
我相信这会奏效……
DELETE FROM LoginTime WHERE id IN (
SELECT id
WHERE user_id = 1
ORDER BY datetime DESC
LIMIT 0,5
)