内部加入laravel多对多关系与索引的慢性能

时间:2017-07-04 08:32:42

标签: mysql laravel-5

首先,我为我的英语水平道歉。

我正在使用laravel多种关系来收集产品。

因此,Laravel会生成如下的查询;

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

产品表:(行数 - 100K)

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

收藏表(行数 - 39K)

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

Product_Collection表(行数470K)

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

高于进度的查询时间高达2.5秒。 (没有索引)

如果我尝试使用以下索引:

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

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

以下查询时间以0秒为单位进行 (此查询结果有3,550行中的15行。)

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

当我尝试“collection_id = 20418”时,查询时间最多可达2秒。 (此查询结果有1行。只有1行:))

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

我只是改变号码。

我做错了什么?

感谢您的帮助。

0 个答案:

没有答案
相关问题