简体   繁体   English

优化mysql查询:产品<-N:N->类别

[英]Optimize mysql query: products <- N:N -> categories

Is there any way to do this query in a more optimized way? 有什么方法可以以更优化的方式执行此查询?

select SQL_NO_CACHE count(*) from products p
INNER JOIN `products_categories` AS `pc` ON p.id = pc.products_id
where pc.categories_id = 87

My schema is simple: products, categories and a N:N join table: products_categories. 我的架构很简单:产品,类别和N:N联接表:products_categories。 Products are about 400000 rows. 产品约有40万行。 products_categories is about 600000. Products with category = 87 are about 18000. Using explain gives: products_categories大约为600000。category = 87的产品大约为18000。使用explain给出:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  pc  index   products_id products_id 8   NULL    612469  Using where; Using index
1   SIMPLE  p   eq_ref  PRIMARY PRIMARY 4   stagingbagthis.pc.products_id   1   Using index

It seems to me that the first line where rows = 612469 is not a very good sign. 在我看来,行= 612469的第一行并不是一个好兆头。 So, can this query be optimized in any way possible? 那么,可以以任何可能的方式优化此查询吗?

What if you removed the products table: 如果删除了products表怎么办:

select SQL_NO_CACHE count(*)
from products_categories` `pc` 
where pc.categories_id = 87;

For this, you would need an index on products_categories(categories_id) , or similar index where categories_id is the first column. 为此,您需要在products_categories(categories_id)上建立一个索引,或者类似的索引,其中categories_id是第一列。

您需要在products_categories.categories_id上建立索引,以便可以优化WHERE子句。

You could try this. 你可以试试看。

select SQL_NO_CACHE count(*) from products p
    INNER JOIN `products_categories` AS `pc` 
        ON p.id = pc.products_id and pc.categories_id = 87

Also check the cardinality of your indexes we have found cases where the cardinality gets out of whack and we need to analyze the tables to get our execution plans back in line. 还要检查索引的基数,我们发现基数超出预期的情况,我们需要分析表以使执行计划恢复正常。

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

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