[英]MySQL update join performance
I need to update several columns in one table, based on columns in another. 我需要根据另一个表中的列更新一个表中的几列。 To start with I am just updating one of them.
首先,我只是更新其中之一。 I have tried 2 ways of doing this, which both work, but they are taking about 4 minutes using mySQL commands, and over 20 when run in php.
我已经尝试了两种方法来完成这项工作,但这两种方法都可行,但是使用mySQL命令大约需要4分钟,而在php中运行则需要20多分钟。 Both tables are about 20,000 rows long.
两个表的长度约为20,000行。
My question is, is there a better or more efficient way of doing this? 我的问题是,有没有更好或更有效的方法?
Method 1: 方法1:
UPDATE table_a,table_b
SET table_a.price = table_b.price
WHERE table_a.product_code=table_b.product_code
Method 2: 方法2:
UPDATE table_a INNER JOIN table_b
ON table_a.product_code = table_b.product_code
SET table_a.price=table_b.price
I guess that these basically work in the same way, but I thought that the join would be more efficient. 我想这些基本上可以以相同的方式工作,但是我认为联接会更有效。 The product_code column is random text, albeit unique and every row matches one in the other table.
product_code列是随机文本,尽管是唯一的,并且每一行都与另一表匹配。
Anything else I can try? 我还能尝试什么吗?
Thanks 谢谢
UPDATE: This was resolved by creating an index eg 更新:这通过创建索引来解决,例如
CREATE UNIQUE INDEX index_code on table_a (product_code)
CREATE UNIQUE INDEX index_code on table_b (product_code)
If your queries are running slowly you'll have to examine the data that query is using. 如果查询运行缓慢,则必须检查查询所使用的数据。
Your query looks like this: 您的查询如下所示:
UPDATE table_a INNER JOIN table_b
ON table_a.product_code = table_b.product_code
SET table_a.price=table_b.price
In order to see where the delay is you can do 为了查看延迟在哪里,您可以执行
EXPLAIN SELECT a.price, b.price FROM table_b b
INNER JOIN table_a a ON (a.product_code = b.product_code)
This will tell you if indexes are being used, see the info on EXPLAIN and more info here . 这将告诉您是否正在使用索引,请参阅EXPLAIN上的信息以及此处的更多信息 。
In your case you don't have any indexes ( possible keys = null
) forcing MySQL to do a full table scan. 在您的情况下,您没有任何索引(
possible keys = null
),迫使MySQL执行全表扫描。
You should always do an explain select
on your queries when slowness is an issue. 当速度缓慢成为问题时,您应该始终对查询进行
explain select
。 You'll have to convert non-select queries to a select
, but that's not difficult, just list all the changed fields in the select clause and copy join
and where
clauses over as is. 您必须将非选择查询转换为
select
,但这并不困难,只需在select子句中列出所有更改的字段,然后原样复制join
和where
子句即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.