2

I'm trying to delete all rows from a table except the one having the max revision_id value simultaneously selecting data from the same table:

delete from
  node_revision__body
where
  entity_id=4 
  and revision_id not in (
    select
      max(revision_id)
    from
      node_revision__body
    where
      entity_id=4
    )

That throws the error

You can't specify target table 'node_revision__body' for update in FROM clause

Is it possible to somehow change the query in order to achieve the goal?

4
  • does it work without the sub-select? as in delete from node_revision__body where entity_id=4 and revision_id not in (1,2,3) Commented Dec 11, 2022 at 16:04
  • only by views I guess... Commented Dec 11, 2022 at 16:04
  • @JoSSte yes, it works without the sub-select Commented Dec 11, 2022 at 16:16
  • and many more duplicates stackoverflow.com/… Commented Dec 11, 2022 at 17:23

1 Answer 1

3

This is a documented "feature" of MySql, you cannot update the same table as you select from, however a few workarounds exist, for example you can try nesting the query one level deeper:

delete from node_revision__body
where entity_id = 4 
  and revision_id not in (
    select revision_id from (
      select max(revision_id) revision_id
      from node_revision__body
      where entity_id = 4
    )b
);

See a working demo

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! Is it a typo )b before the last row?
that is a shorthand as b
I haven't tried the code but no, b is the required derived table alias.
@Stu I don't know why, but it doesn't work. I get "0 rows affected" and when I run select, I still see all the rows in the table
@stckvrw I spotted the possible problem I think, I edited above, the max(revision_id) should also be aliased otherwise it won't exist for the outer query - see working Fiddle
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.