0

我正在使用 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 中的条目数。

我可以对如何优化这个有一些建议吗?

谢谢。

4

1 回答 1

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
...

于 2013-10-10T19:14:31.853 回答