想要在添加新记录时删除最旧的记录,不超过5条记录

时间:2015-07-29 23:38:33

标签: mysql sql

我有下表:

id      user_id     message     timestamp
----    -------     --------    ----------
1        abc        message1    2015-07-27 19:10:40
2        def        message1    2015-07-27 19:20:41
3        xyz        message1    2015-07-27 19:30:41
4        abc        message2    2015-07-28 19:11:40
5        abc        message3    2015-07-28 19:12:40
6        abc        message4    2015-07-28 19:13:40
7        abc        message5    2015-07-28 19:14:40

当用户' abc'添加第6条消息,我希望删除第1条(最旧的)。

我正在尝试以下两个SQL查询,但它只留下5条消息,而不考虑user_id

INSERT INTO sample(user_id, message, created)
VALUES('abc', 'message6', now());

DELETE FROM sample 
WHERE user_id = 'abc' 
  AND id NOT IN (SELECT id 
                 FROM 
                     (SELECT id 
                      FROM sample 
                      ORDER BY id DESC 
                      LIMIT 5) x 
                ); 

提前致谢

1 个答案:

答案 0 :(得分:2)

您在第二个查询中缺少用户选择。

此外,正如Jorge Campos强调的那样,您应该按日期排序,以便将现有邮件的编辑/更新视为最新邮件,而不是旧邮件。

尝试

INSERT INTO sample(user_id,message,created)
VALUES('abc','message6',now());

DELETE FROM sample WHERE user_id = 'abc' AND id NOT IN ( 
  SELECT id 
  FROM ( 
    SELECT id 
    FROM sample WHERE user_id = 'abc'
    ORDER BY created DESC 
    LIMIT 5
    ) x 
  );