0

I have 2 Entities Item and Image. An Item can have multiple Images.

If an Item has more than 4 Image(s) I want to delete the ones above, ordered by id

Structure:

Item

id | name
1    a
2    b
3    c

Image

id | item_id
1    1
2    1 
3    2
user3541631
  • 3,686
  • 8
  • 48
  • 115
  • You can use this to identify which should be kept and which should be removed : https://stackoverflow.com/questions/1124603/grouped-limit-in-postgresql-show-the-first-n-rows-for-each-group – sagi Dec 16 '18 at 12:52

2 Answers2

1

You could use:

DELETE FROM Image
WHERE id IN (SELECT sub.id
             FROM (SELECT im.id,
                    ROW_NUMBER() OVER(PARTITION BY i.id ORDER BY im.id) AS rn
                   FROM Item i
                   JOIN Image im
                     ON i.id = im.item_id) sub
             WHERE sub.rn > 4);

Before you run DELETE check if subquery returns desired ids.

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
1

I would do:

delete from image
where id < (select i2.id
            from image i2
            where i2.item_id = i.item_id
            order by id desc
            limit 1 offset 3
           );

This deletes any id that is less than the fourth largest id for a given item_id.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786