有没有办法优化这个MYSQL查询

时间:2013-10-04 08:00:17

标签: mysql sql query-optimization

我有一个MySql表,其中包含以下架构。

table_products - "product_id", product_name, product_description, product_image_path, brand_id
table_product_varient - "product_id", "varient_id", product_mrp, product_sellprice, product_imageurl
table_varients - "varient_id", varient_name
table_product_categories - "product_id", "category_id"

这是我用来获取所提供类别用户的数据的Mysql select查询。

select * from table_products, table_product_varients, table_varients, table_product_categories where table_product_categories.category_id = '$cate_id' && table_product_categories.product_id = table_products.product_id && table_products.product_id = table_product_varients.product_id && table_varients.varient_id = table_product_varients.varient_id

问题在于,由于表包含大量产品,并且每个产品都包含大量变量,因此获取数据需要花费太多时间。我怀疑,随着数据的增长,获取物品的时间会增加。是否有任何优化的方法来实现相同的目标。

我们非常感谢您的帮助。

Devesh

3 个答案:

答案 0 :(得分:2)

您可以使用EXPLAIN命令查看服务器中发生的事情。然后,您可以通过创建索引来优化请求。

一些链接:

答案 1 :(得分:2)

下面的查询将是一个开头,或类似的东西

SELECT
    * 
FROM
    table_products P
INNER JOIN
    table_product_categories PC 
ON
    PC.product_id = P.product_id
INNER JOIN
    table_product_varients PV
ON
    P.product_id = PV.product_id
INNER JOIN
    table_varients V
ON
    V.varient_id = PV.varient_id
where 
    table_product_categories.category_id = '$cate_id' 

并且按照建议你真的需要返回*,因为这意味着从查询中的所有表中选择所有列,正如我们从连接本身那样知道重复项。

您应该对表使用索引以获得更快的查询,设置连接表之间的关系,这也将确保参照完整性。

希望这有意义并有所帮助:)

答案 2 :(得分:1)

是的,你是对的,你上面使用的查询效率不高:

您可以使用ON子句而不是where子句获得与上面相同的结果。

它们之间的区别在于,where子句获取所有行,然后根据指定的condidition过滤掉。

在ON子句的情况下,连接仅发生在符合ON子句中指定的条件的行上

所以......如下所示制作您的查询:

所以使用连接而不是使用where子句..

希望这会有所帮助..