Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete statement in a same table

Tags:

I need to query a delete statement for the same table based on column conditions from the same table for a correlated subquery.

I can't directly run a delete statement and check a condition for the same table in mysql for a correlated subquery.

I want to know whether using temp table will affect mysql's memory/performance?

Any help will be highly appreciated.

Thanks.

like image 821
Sharpeye500 Avatar asked Jul 27 '10 17:07

Sharpeye500


People also ask

How do I DELETE multiple records in a table?

There are a few ways to delete multiple rows in a table. If you wanted to delete a number of rows within a range, you can use the AND operator with the BETWEEN operator. DELETE FROM table_name WHERE column_name BETWEEN value 1 AND value 2; Another way to delete multiple rows is to use the IN operator.

Does DELETE statement maintains any lock on table?

DELETE statement uses a row lock while executing. Each row in the table is locked for deletion. You can specify filters in WHERE clause.


2 Answers

You can make mysql do the temp table for you by wrapping your "where" query as an inline from table.

This original query will give you the dreaded "You can't specify target table for update in FROM clause":

DELETE FROM sametable WHERE id IN (     SELECT id FROM sametable WHERE stuff=true ) 

Rewriting it to use inline temp becomes...

DELETE FROM sametable WHERE id IN (  SELECT implicitTemp.id from (SELECT id FROM sametable WHERE stuff=true) implicitTemp ) 
like image 199
Adam Lane Avatar answered Oct 27 '22 23:10

Adam Lane


Your question is really not clear, but I would guess you have a correlated subquery and you're having trouble doing a SELECT from the same table that is locked by the DELETE. For instance to delete all but the most recent revision of a document:

DELETE FROM document_revisions d1 WHERE edit_date <    (SELECT MAX(edit_date) FROM document_revisions d2     WHERE d2.document_id = d1.document_id); 

This is a problem for MySQL.

Many examples of these types of problems can be solved using MySQL multi-table delete syntax:

DELETE d1 FROM document_revisions d1 JOIN document_revisions d2    ON d1.document_id = d2.document_id AND d1.edit_date < d2.edit_date; 

But these solutions are best designed on a case-by-case basis, so if you edit your question and be more specific about the problem you're trying to solve, perhaps we can help you.

In other cases you may be right, using a temp table is the simplest solution.

like image 36
Bill Karwin Avatar answered Oct 27 '22 21:10

Bill Karwin