Laravel Query Builder orderBy id DESC在100k行上运行速度非常慢



我有一个装满100k产品的数据库,这是我的查询

$products = DB::table('product')
->leftJoin('product_description', 'product_description.product_id', 'product.product_id')
->leftJoin('product_to_category','product_to_category.product_id','product.product_id')
->select(self::$select_fields)
->where('product_description.language', $language)
->groupBy('product.product_id');
if (!empty($filter->keyword)) {
$products->where('product_description.title','LIKE','%'. $filter->keyword .'%');
}
if (!empty($filter->category_id)) {
$products->where('product_to_category.category_id','=',$filter->category_id);
}

if (!empty($filter->range)) {
$range= explode(',',$filter->range);
$products->whereBetween('product.price', [$range[0], (!empty($range[1]))? $range[1] : $range[0]]);
}

return $products->orderBy('product.product_id','DESC')->where('product.status',1)->limit(50);

此查询将在12.6秒内加载。如果我删除->orderBy('product.product_id','DESC'),查询将在0.800ms内运行。

在我的数据库中,我有productdescription.product_idproduct_to_category.product_id品的索引键。id设置为主

我已经看到orderBY desc在大型数据库中速度减慢了很多,有没有解决方法,我需要通过desc进行订购,因为我想要";最新的";上传后,我尝试将其设置为";created_ at";列,但它大约是相同的

编辑

我尝试过不使用Laravel,基本上速度差不多,按DESC排序会减慢查询速度,有没有解决方案?或者基本上DESC只是很慢,应该避免使用BIG数据库?

您按product.product_id分组,而我猜测选择仅包含产品表中的列。在这种情况下,可以删除左边的联接,或者用现有的查询替换。可以完全删除分组。联接将行相乘,并通过压缩行进行分组;删除后,查询变得更简单,希望更快:

select foo, bar, baz
from product
where status = ?
and price between ? and ? -- add this where clause if you need to filter on product price
and exists ( -- add this subquery if you need to filter on description language and/or title
select 1
from product_description
where product_description.product_id = product.product_id
and product_description.language = ?
and product_description.title like ?
)
and exists ( -- add this subquery if you need to filter on category id
select 1
from product_to_category
where product_to_category.product_id = product.product_id
and product_to_category.category_id = ?
)
order by product_id desc
limit 50

我认为您可以定义DESC索引,因为列上的默认索引是ASC

例如:

CREATE INDEX product_index ON product (product_id DESC);

更多信息

最新更新