3

I want to delete an entry in a table where multiple fields match the results of another select subquery which takes data from another table.

This is what I have so far, though it doesn't work:

DELETE FROM table1
WHERE table1.id IN
 (SELECT id
 FROM table1 a JOIN table2 b
 ON a.field1 = b.field1
 AND a.field2 = b.field2
 AND a.field3 = b.field3
 AND b.id = ?
 )
RolandoMySQLDBA
185k34 gold badges327 silver badges541 bronze badges
asked Jun 4, 2013 at 16:05
1
  • How it doesn't work? Is it working but slow? It is not deleting what you want? Is it throwing error? Commented Jun 4, 2013 at 16:39

1 Answer 1

6

Perhaps the DELETE JOIN would be preferable

DELETE A.* FROM table1 A INNER JOIN table2 b
ON A.id = B.id
AND a.field1 = b.field1
AND a.field2 = b.field2
AND a.field3 = b.field3
AND b.id = ?;

I wrote about why DELETE with WHERE involving a subquery is sort of unhealthy to deal with in a past post of mine back on Feb 22, 2011: Problem with MySQL subquery

Even though there have been great strides in improving the Query Optimizer, evaluation of subqueries could make keys unavailable for key comparisons downstream.

ALTERNATIVE

Try gathering the keys you know need to be deleted and do the DELETE JOIN with it:

CREATE TABLE DeleteIDs SELECT id FROM table1 WHERE 1=2;
INSERT INTO table1
 SELECT A.id FROM table1 A INNER JOIN table2 b
 ON A.id = B.id
 AND a.field1 = b.field1
 AND a.field2 = b.field2
 AND a.field3 = b.field3
 AND b.id = ?
;
ALTER TABLE DeleteIDs ADD PRIMARY KEY (id);
DELETE B.* FROM DeleteIDs A INNER JOIN table1 B;
DROP TABLE DeleteIDs;

SUGGESTION

Maybe an index would help

ALTER TABLE table1 ADD INDEX id123 (id,field1,field2,field3);
ALTER TABLE table2 ADD INDEX id123 (id,field1,field2,field3);

Give it a Try !!!

answered Jun 4, 2013 at 16:23
4
  • Why do you write DELETE A.* FROM .... instead of DELETE A FROM ....? Isn't the * needlessly redundant? Commented Apr 10, 2015 at 14:22
  • @Pacerier that's how I learned it 20 years doing Microsoft Access development. MySQL accepts it. So, it's just an old habit. Commented Apr 10, 2015 at 14:24
  • However it's somewhat wrong since it seems to suggest that you can do a delete a.Column2 when really it deletes the entire row. Commented Apr 11, 2015 at 15:39
  • 2
    @Pacerier If it's in the SQL standard, - by definition - it is not wrong ;) Commented Apr 14, 2015 at 18:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.