小编典典

在表格中仅保留用户的最后5个搜索结果

sql

我需要将用户的最后5个搜索结果保留在一个表中。
我写了一个脚本来删除其他行,但是没有用:

DELETE FROM         
    SELECT
        ROW_NUMBER () OVER (ORDER BY search_time DESC) AS row_number;
    FROM
        history_user
    WHERE
        user_id = 188
WHERE row_number>5

我做错什么了?


阅读 212

收藏
2021-04-07

共1个答案

小编典典

正确的语法,如手册中所述

DELETE FROM history_user h
USING (
    SELECT pk_id, row_number() OVER (ORDER BY search_time DESC) AS rn;
    FROM   history_user
    WHERE  user_id = 188
    ) sub
WHERE sub.rn > 5
AND   h.pk_id = sub.pk_id;

唯一的pk_id列(组合)在哪里?在您的情况下,可能是-或更方便的是代理主键。 __user_id``search_time

对于只是一个 单一的 user_id,你可以简化为:

DELETE FROM history_user h
USING (
    SELECT pk_id
    FROM   history_user
    WHERE  user_id = 188
    ORDER  BY search_time DESC
    OFFSET 5
    ) sub
WHERE h.pk_id = sub.pk_id;

另一方面,要一次处理 多个 用户,您需要添加PARTITION BY到window函数:

DELETE FROM history_user h
USING (
    SELECT pk_id, row_number() OVER (PARTITION BY user_id
                                     ORDER BY search_time DESC) AS rn;
    FROM   history_user
    ) sub
WHERE sub.rn > 5
AND   h.pk_id = sub.pk_id;
2021-04-07