Sunday, June 30, 2013

MySQL - delete from a table with a subquery on the same table

Assume you have a table called story with columns id, content and status. 

Table schema:
CREATE TABLE `story` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` longtext NOT NULL,
  `status` smallint(6) NOT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB ;
We want to delete all the records that have status 3 and id less than 6022.

You may do the following:
delete from story where id in (select id from story where status = 3 and id < 6022);
However, this does not work.
ERROR 1093 (HY000): You can't specify target table 'story' for update in FROM clause
Instead, you need to wrap the subquery in an abstract table with an alias (called old_featured below).
delete from story where id in (select * from (select id from story where status = 3 and id < 6022) as old_featured);

2 comments:

  1. Big help for me, thank you very much.

    ReplyDelete
  2. Thanks, it's what I need to avoid a query to get the id of the table and then delete.

    ReplyDelete