我正在使用MySQL 5.5,我有以下sql:
UPDATE t SET val = 1 WHERE id IN ( SELECT id FROM temp1);
UPDATE t SET val = 2 WHERE id IN ( SELECT id FROM temp2 );
UPDATE t SET val = 3 WHERE id IN ( SELECT id FROM temp3 );
UPDATE t SET val = 4 WHERE id IN ( SELECT id FROM temp4 );
UPDATE t SET val = 5 WHERE id IN ( SELECT id FROM temp5 );
UPDATE t SET val = 6 WHERE id IN ( SELECT id FROM temp6 );
UPDATE t SET val = 7 WHERE id IN ( SELECT id FROM temp7 );
UPDATE t SET val = 8 WHERE id IN ( SELECT id FROM temp8 );
UPDATE t SET val = 9 WHERE id IN ( SELECT id FROM temp9 );
UPDATE t SET val = 10 WHERE id IN ( SELECT id FROM temp10 );
temps是我使用的TEMPORARY表,该表有大约10k个条目,完成此sql语句的执行大约需要30秒。临时表中所有条目的总和也等于t中的条目数。
我可以就如何优化这个提出一些建议吗?感谢。
答案 0 :(得分:1)
首先检查id
列的“t”是否有索引(主键是最佳索引)
然后尝试使用以下内容对您的变体进行基准测试:
1
update t, (
select 1 as v, id from temp1
union all
select 2, id from temp2
...
) as q set val=q.v where t.id=q.id
2
truncate table t; -- note deletion of all from table t
insert into t (id, val)
select id, val from temp1
union all
select id, val from temp2
...