如何在php文件中优化此代码

时间:2014-03-21 02:31:23

标签: php mysql sql optimization tmp

最近我们的服务器提供商告诉我们,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');

如何优化此功能,有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

不确定product_feature_descriptions与产品功能之间的表结构。如果product_features与product_feature_descriptions有一对多,那么您似乎应该进行内连接而不是左连接。

无论如何,放弃" distinct"然后按"尝试一个"组。

这将提高绩效。

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

答案 1 :(得分:0)

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

  • 在product_features上有一个索引(feature_id,parent_id,feature_type) &安培;在product_features_descriptions上(feature_id,description,lang_code)

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