I have two tables.
tb_users
id (pk)
login_name
tb_test
id (pk)
user_id
user_code
The sample date is like below
tb_users (id, login_name)
11e8, tom
11e3, jerry
11e1, peter
... 49316 more items
tb_test (id,user_id,user_code)
ff3f10b01, ,tom
ff3f10b02, ,tom
ff3f10b03, ,tom
ff3f10b04, ,peter
... 70000 more items
Now I need to update field 'user_id' in tb_test with 'id' in tb_user. I wrote the sql.
update tb_test a
set a.user_id = (select b.id
from tb_user b
where a.user_code = b.login_name )
It takes more than 1 minute! I wrote the select sql, it runs very fast. How should I improve the update efficiency?
select a.*, b.id
from tb_test a, tb_user b
where a.user_code = b.login_name
The result should be like this
tb_test (id,user_id,user_code)
ff3f10b01, 11e8 ,tom
ff3f10b02, 11e8 ,tom
ff3f10b03, 11e8 ,tom
ff3f10b04, 11e1 ,peter
... 70000 more items
First, I would recommend writing this as a join
:
update tb_test t join
tb_user u
on t.user_code = u.login_name
set t.user_id = u.id;
Then, for performance, you want an index on tb_user(login_name, id)
.
That said, you are updating almost all rows. In many cases, it is cheaper just to recreate the table:
create table temp_tb_test as
select t.id, u.id as user_id, t.user_code
from tb_test t left join
tb_user u
on t.user_code = u.login_name;
truncate table tb_test; -- be very cautious here!
insert into tb_test(id, user_id, user_code)
select id, user_id, user_code
from temp_tb_test;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.