Scott Chu
Scott Chu

Reputation: 990

How to avoid full table scan when update with IN clause in MySQL

I got 2 MySQL tables: termlist and blacklist. They both have index on field 'term' and blacklist has another index on field 'status'.

I want to update status of terms in termlist, that also appear in blacklist with status as 'A', to 'B', I issue this SQL statement:

update termlist set status = 'B' where term in (select term from blacklist where status = 'A')

It cause a full table scan on termlist. I want to use 'update with inner join' but I can't since there's a where clause in select statement.

I know I can create a temp table from that select statement and then update inner join with that temp table but this is kinda tedious if I want to do this update many times.

Is there one single update statement that can do the work without full table scan?

Upvotes: 1

Views: 1431

Answers (1)

Ormoz
Ormoz

Reputation: 3013

You may use:

update termlist t inner join blacklist b 
    on t.term=b.term
    set t.status = 'B' 
    where b.status = 'A'

Upvotes: 2

Related Questions