gpt4 book ai didi

mysql - 删除除最后三个记录之外的记录

转载 作者:可可西里 更新时间:2023-11-01 06:41:07 28 4
gpt4 key购买 nike

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

最佳答案

试试这个:

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 |

关于mysql - 删除除最后三个记录之外的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21015125/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com