【问题标题】:MySQL Update Based on ID Slow (150,000 records)MySQL 更新基于 ID 慢(150,000 条记录)
【发布时间】:2016-04-18 04:30:23
【问题描述】:

我正在尝试根据另一个表上的 id 更新一个表,但我遇到了一些性能问题。我在 table_to_update 上有 150,000 行,在 table_to_get_data 上有 400,000 行。

要更新的表 +----+-----------------+ | id | field_to_update | +----+-----------------+ | 1 | orange | | 2 | apple | | 3 | pear | | 1 | orange | +----+-----------------+

获取数据的表 +----+-----------------+ | id | field | +----+-----------------+ | 1 | orange | | 2 | apple | | 3 | pear | +----+-----------------+

所以我尝试了 3 种不同的方法:

方法一:

UPDATE table_to_update t1, table_to_get_data t2
SET t1.field_to_update = t2.field
WHERE t1.id = t2.id

方法二:

UPDATE table_to_update
JOIN table_to_get_data
ON table_to_update.id = table_to_get_data.id
SET table_to_update.field_to_update = table_to_get_data.field

方法三:

UPDATE table_to_update
LEFT JOIN table_to_get_data
ON table_to_update.id = table_to_get_data.id
SET table_to_update.field_to_update = table_to_get_data.field

到目前为止,方法 3 似乎是最快的,但是,计算更新 1000 行所需的时间,我需要 12 个小时才能完成整个表的更新。有没有更高效的方法来更新表格?

编辑: 添加了解释表 EXPLAIN Table

【问题讨论】:

  • 列是否按应有的方式编入索引?您也可以尝试运行EXPLAIN <query> 以查看查询将如何执行。
  • 显示您的创建表查询并在每三个 sql 方法之前运行 Explain。
  • 向我们展示您的疑问的解释
  • 谢谢,EXPLAIN 表可以找到here

标签: mysql sql database query-performance


【解决方案1】:

在您从两个表连接的列上创建索引。

它会为你创造奇迹。

【讨论】:

  • 我没有添加任何索引,但是根据w3schools,索引非常适合搜索,但可能需要更多时间来更新。
  • 我不同意这一点。添加索引并自己尝试。如果没有帮助,您可以随时删除索引。
  • 当然,会试一试。谢谢。
  • 哇哦,添加索引已将 12 小时的查询缩短到不到 10 秒!谢谢!!
  • "索引非常适合搜索" -- 您正在 table_to_get_data 中搜索。 “但需要更多时间来更新”——这比另一个重要。
猜你喜欢
  • 1970-01-01
  • 2015-07-22
  • 2014-02-27
  • 2018-07-17
  • 2015-02-15
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
相关资源
最近更新 更多