【问题标题】:how to optimize this code in php file如何在 php 文件中优化此代码
【发布时间】:2014-03-21 02:31:22
【问题描述】:

最近我们的服务器提供商告诉我们,Mysql 在磁盘上创建了许多 tmp 表,并导致磁盘 I/O 滥用。我认为这是因为下面的代码:

$features = db_get_array("SELECT DISTINCT(a.description), b.parent_id FROM ?:product_features_descriptions as a LEFT JOIN ?:product_features as b ON a.feature_id = b.feature_id WHERE a.lang_code = ?s AND b.feature_type != ?s ORDER BY b.parent_id, a.description ASC", DESCR_SL, 'G');

我该如何优化这个,有人可以帮我吗?

【问题讨论】:

标签: php mysql sql optimization tmp


【解决方案1】:

不确定 product_feature_descriptions 和 product features 之间的表结构是什么。如果 product_features 与 product_feature_descriptions 一对多,您似乎应该进行内连接而不是左连接。

无论如何,放弃“distinct”并尝试“group by”。

这将提高性能。

SELECT a.description
,b.parent_id 
FROM ?:product_features_descriptions as a 
LEFT JOIN ?:product_features as b 
ON a.feature_id = b.feature_id 
WHERE a.lang_code = ?s 
AND   b.feature_type != ?s 
GROUP BY a.description, b.parent_id
ORDER BY b.parent_id, 
a.description ASC

【讨论】:

    【解决方案2】:

    为了提高性能,还要检查数据库中 product_features_descriptions 和 product_features 表的索引。

    • 在 product_features 上有一个索引(feature_id、parent_id、feature_type) & on product_features_descriptions (feature_id,description,lang_code)

    这应该使优化器从索引中访问数据并提高性能

    【讨论】:

      猜你喜欢
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 2020-09-02
      相关资源
      最近更新 更多