在Postgres中删除除了最大n组的所有组

时间:2017-11-01 19:40:31

标签: sql postgresql greatest-n-per-group

如果我有两个Postgres表,请说

CREATE TABLE store (
    id text,
    name text
)

CREATE TABLE product (
    store_id text,
    id text,
    created_at timestamp
)

我知道我可以用

获得最新产品的表格
SELECT product.*
FROM store JOIN (SELECT DISTINCT ON (store_id)
                 FROM product ORDER BY store_id, created_at DESC)
           AS newest_product_by_store
ON newest_product_by_store.store_id = store.id

那么,如何删除不在newest_product_by_store中的所有产品的删除操作?

2 个答案:

答案 0 :(得分:2)

防弹方式:

delete from product
where id not in (
    select a.id
    from (
        select p.id
        from product p
        inner join (
            select store_id, max(created_at)
            from product
            group by store_id
            ) b
            on p.store_id = b.store_id
                and p.created_at = b.created_at
        ) a
    )

假设您的ID自动增加,而您无法及时插入created_at

delete from product 
where id not in (
  select a.id 
  from (
    select max(id) as id
    from product 
    group by store_id
    ) a
)

答案 1 :(得分:0)

这是一种方法:

delete from product p
    using (SELECT DISTINCT ON (store_id) p.*
          FROM product p
          ORDER BY store_id, created_at DESC
         ) ps
    where p.store_id = ps.store_id and p.created_at < ps.created_at;

这通常是在没有子查询的情况下编写的:

delete from product p
    where p.created_at < (select max(p2.created_at) from product p2 where p2.store_id = p.store_id);