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. Products are about 400000 rows. products_categories is about 600000. Products with category = 87 are about 18000. Using explain gives:
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. So, can this query be optimized in any way possible?
What if you removed the products
table:
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
上建立索引,以便可以优化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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.