删除最近三条记录以外的记录

时间:2014-01-09 08:31:08

标签: mysql sql greatest-n-per-group sql-delete records

我有一个log表,我想删除除最后三条记录之外的每个用户的记录。

模式

DROP TABLE IF EXISTS `log`;
CREATE TABLE `log` (
  `user_id` int(11) DEFAULT NULL,
  `timestamp` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

insert  into `log`(`user_id`,`timestamp`) values (1,1389257013),(1,1389257014),(1,1389257015),(1,1389257016),(1,1389257017),(2,1389257018),(2,1389257019),(2,1389257020),(2,1389257021),(2,1389257022),(3,1389257023),(3,1389257024);

当前表:

id    timestamp
1     1389257013
1     1389257014
1     1389257015
1     1389257016
1     1389257017
2     1389257018
2     1389257019
2     1389257020
2     1389257021
2     1389257022
3     1389257023
3     1389257024

预期表格

id    timestamp    
1     1389257015
1     1389257016
1     1389257017
2     1389257020
2     1389257021
2     1389257022
3     1389257023
3     1389257024

2 个答案:

答案 0 :(得分:7)

试试这个:

DELETE l FROM `log` l 
WHERE NOT EXISTS (
          SELECT 1
          FROM (SELECT l.user_id, l.timestamp, 
                       IF(@lastUserId = @lastUserId:=user_id, @Idx:=@Idx+1, @Idx:=0) rowNumber 
                FROM `log` l, (SELECT @lastUserId:=0, @Idx:=0) A
                ORDER BY l.user_id, l.timestamp DESC
               ) AS A
          WHERE l.user_id= A.user_idAND l.timestamp = A.timestamp AND rowNumber < 3
         );

检查SQL FIDDLE DEMO

<强>输出

| USER_ID |  TIMESTAMP |
|---------|------------|
|       1 | 1389257015 |
|       1 | 1389257016 |
|       1 | 1389257017 |
|       2 | 1389257020 |
|       2 | 1389257021 |
|       2 | 1389257022 |
|       3 | 1389257023 |
|       3 | 1389257024 |

答案 1 :(得分:4)

尝试以下SQL:

DELETE FROM log WHERE find_in_set(
    TIMESTAMP, (
        SELECT group_concat(t3) t4 FROM (
            SELECT 1 AS dummy,
            replace(group_concat(TIMESTAMP ORDER BY TIMESTAMP DESC), concat(SUBSTRING_INDEX(group_concat(TIMESTAMP ORDER BY TIMESTAMP DESC), ',', 3), ','), '') t3
            FROM log
            GROUP BY user_id HAVING count(*) > 3
        ) a GROUP BY dummy
    )
)

SQL Fiddle