3

我有这张桌子:

| Column        | Type                           |
+---------------+--------------------------------+         
| id            | integer                        |
| recipient_id  | integer                        | 
| is_read       | boolean                        | 
| updated_at    | timestamp(0) without time zone | 

我必须使用以下特定规则从该表中删除项目:

  • 对于每个recipient_id,我们保留最后阅读的 5 个项目,并删除旧的阅读项目。

我试图用RECURSIVE WITH陈述来改变我的想法,但惨遭失败。我已经以编程方式实现了我的解决方案,但我想知道是否有一个像样的纯 SQL 解决方案。

4

3 回答 3

2
DELETE FROM tbl t
USING (
    SELECT id, row_number() OVER (PARTITION BY recipient_id
                                  ORDER BY updated_at DESC) as rn
    FROM   tbl
    WHERE  is_read
  ) x
WHERE  x.rn > 5
AND    x.id = t.id;

AJOIN通常比 IN 表达式快,尤其是在项目数量较多的情况下。
并用row_number(),不行rank()

于 2012-10-11T16:39:11.587 回答
0

查看窗口功能

DELETE FROM table
WHERE id IN (
  SELECT id
  FROM (
    SELECT id, rank() OVER (PARTITION BY recipient_id ORDER BY updated_at DESC) as position
    FROM table
    WHERE is_read
  ) subselect WHERE position > 5
)
于 2012-10-11T16:33:44.440 回答
0
delete from t
where id in (
    select id
    from (
        select 
            id, 
            row_number() over(partition by recipient_id order by updated_at desc) rn
        from t
        where is_read
    ) s
    where s.rn > 5
)
于 2012-10-11T16:33:13.553 回答