mardi 4 juillet 2017

Inner Join for laravel many to many relationship slow performance with index

First of all i apologize for my english level.

I'm using laravel many to many relationship for collections and products.

So, Laravel produces a query like the following;

select * from `products` inner join 
`product_collection` on `products`.`id` = `product_collection`.`product_id`
 where `product_collection`.`collection_id` = 3 order by `stockDate` desc 
limit 15 offset 0

Products Table : (Row Count - 100K)

products
id - (int)
title - (string)
description - (string)
imagePath - (string)
stockDate - (timestamp)
vs.

Collections Table (Row count - 39K)

id - (int)
title - (string)
slug - (string)
vs.

Product_Collection Table (Row Count 470K)

id - (int)
product_id - (int)
collection_id - (int)

Query time above progresses goes up to 2.5 second. (Without indexes)

If i try with following indexes :

ALTER TABLE `product_collection` ADD INDEX `index_for_pc` (`product_id`,`collection_id`);

ALTER TABLE `products` ADD INDEX `index_for_p` (`stockDate` desc);

Query time below progresses in 0 second (This query result has 15 row out of 3,550 row.)

select * from `products` inner join 
`product_collection` on `products`.`id` = `product_collection`.`product_id`
 where `product_collection`.`collection_id` = 3 order by `stockDate` desc 
limit 15 offset 0

When i try "collection_id=20418" query time goes up to 2 seconds. (This query result has 1 row. Just 1 row :))

select * from `products` inner join 
`product_collection` on `products`.`id` = `product_collection`.`product_id`
 where `product_collection`.`collection_id` = 20418 order by `stockDate` desc 
limit 15 offset 0

explain select

I just changing the number.

What am I doing wrong?

Thanks for help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire