0

Imagine that you have two tables.

Table bar:

+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+

Table foo:

+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| name_alternative | varchar(255) | YES  |     | NULL    |       |
+------------------+--------------+------+-----+---------+-------+

And you want to remove the rows from table bar that have the same name value as the field name_alternative from table foo

I could use the following query:

DELETE FROM foo WHERE name IN (SELECT name_alternative FROM bar);

But this takes a very long time to execute having a large amount of records in both tables.

So I was wondering if there is a better alternative to this query.

3 Answers 3

1

This is another way that would work, and I think it would be more efficient:

DELETE FROM bar
    USING foo, bar
    WHERE name_alternative = name

Here is a working SQLFiddle example.

See the documentation for delete.

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

3 Comments

This generates the following error message: ERROR 1109 (42S02): Unknown table 'bar' in MULTI DELETE
I think this is the correct answer: DELETE FROM bar USING foo, bar WHERE name_alternative = name; could you correct it in order to mark your answer as accepted?
@rfc1484, sorry for the typo. It is corrected now and has a working example.
1

Besides @dan1{4} answer, my guess is that it takes a long time because there is no index on bar(name).

You don't need an index covering the whole 255 chars, depending on your strings, ie if the first characters are different on a lot of rows, create an index on a few characters

CREATE INDEX indexname ON bar(name(8))

8 is a suggested value that you may want to refine. The index will help mysql to locate each bar row that matches a foo.namealternative

Comments

0
delete from bar
using (
    select foo.name_alternative
    from 
        bar
        inner join
        foo on bar.name = foo.name_alternative
) s
where bar.name = s.name_alternative

Comments

Your Answer

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.