2014-01-09 116 views
6

我有一個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 

回答

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

+0

好多了!!這比以前的解決方案稍短。 – neeraj

+0

我很高興你喜歡這個解決方案。 – kwelsan

7

試試這個:

DELETE l FROM `log` l 
WHERE NOT EXISTS (
      SELECT 1 
      FROM (SELECT l.user_id, l.timestamp, 
         IF(@lastUserId = @lastUserId:=user_id, @Idx:[email protected]+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 | 
+2

它藉機d!。你能解釋一下邏輯嗎? – neeraj

+0

是否可以針對同一個問題編寫查詢,其中MAX('timestamp')被發現三次,user_id小於同一用戶的最後一條記錄? – neeraj

+0

@neeraj內部查詢將生成用戶唯一的行號。 –