繁体   English   中英

有什么方法可以优化此MYSQL查询

[英]Is there any way to optimize this MYSQL query

我有一个具有以下架构的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

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

一些链接:

下面的查询将是一个开始,或类似的内容

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' 

并建议您确实需要返回*因为这确实意味着从查询中的所有表中选择所有列,正如我们从联接本身所知的那样,那里存在重复项。

您应该在表上使用索引以加快查询速度,并设置联接表之间的关系,这也将确保引用完整性。

希望这有道理并能帮助:)

是的,您是正确的,上面使用的查询效率不高:

通过使用ON子句而不是where子句,可以获得与上述相同的结果。

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

与ON子句一样,联接仅在满足ON子句中指定的条件的行上发生

所以..进行如下查询:

因此,请使用联接,而不要使用where子句。

希望这可以帮助..

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM