如何删除所有超过一天但从第五行开始的行(如果存在!)?
MYSQL数据库的布局:
user |post|timestamp
Harry foo 1445275458
(时间戳是CURRENT_TIMESTAMP)
答案 0 :(得分:0)
鉴于此示例数据被Drew无耻地窃取并延长:
select t1.*, from_unixtime(tstamp) from t1;
| id | fname | lname | tstamp | from_unixtime(tstamp) |
|----|-------|-------|------------|---------------------------|
| 1 | Harry | foo | 1445275458 | October, 19 2015 17:24:18 |
| 2 | Harry | foo | 1445275457 | October, 19 2015 17:24:17 |
| 3 | Harry | foo | 1445275456 | October, 19 2015 17:24:16 |
| 4 | Harry | foo | 1445275455 | October, 19 2015 17:24:15 |
| 5 | Harry | foo | 1445275454 | October, 19 2015 17:24:14 |
| 6 | Harry | foo | 1445275453 | October, 19 2015 17:24:13 |
| 7 | Harry | foo | 1445275452 | October, 19 2015 17:24:12 |
| 8 | Harry | foo | 1345275458 | August, 18 2012 07:37:38 |
| 9 | Harry | foo | 1435275458 | June, 25 2015 23:37:38 |
使用此查询
DELETE t1.*
FROM t1
LEFT JOIN (SELECT id FROM t1 ORDER BY tstamp DESC LIMIT 5) q ON t1.id = q.id
WHERE q.id IS NULL
AND t1.tstamp < NOW() - INTERVAL 1 DAY;
您会得到以下结果:
select t1.*, from_unixtime(tstamp) from t1;
| id | fname | lname | tstamp | from_unixtime(tstamp) |
|----|-------|-------|------------|---------------------------|
| 1 | Harry | foo | 1445275458 | October, 19 2015 17:24:18 |
| 2 | Harry | foo | 1445275457 | October, 19 2015 17:24:17 |
| 3 | Harry | foo | 1445275456 | October, 19 2015 17:24:16 |
| 4 | Harry | foo | 1445275455 | October, 19 2015 17:24:15 |
| 5 | Harry | foo | 1445275454 | October, 19 2015 17:24:14 |