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

时间:2014-10-22 16:34:59

标签: sql postgresql rows sql-delete

我需要将用户的最后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

我做错了什么?

1 个答案:

答案 0 :(得分:5)

正确的语法as detailed in the manual

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_idsearch_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添加到您的窗口函数中:

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;