【问题标题】:How to optimize Query for Laravel如何优化 Laravel 的查询
【发布时间】:2019-07-03 20:10:24
【问题描述】:

我有超过 60k 条记录,我使用 Has() 通过关系获取记录,但分页速度超过 5 秒,查询速度超过 2 秒。

$products = Item::has('product_save');

我的查询:

select * from `products` where exists (select * from `product_saves` where `products`.`id` = `product_saves`.`product_id` and `user_id` = 2)

我使用 Item 做相同的条件并通过 where() 过滤。喜欢 5 到 88 之间的产品是否仍然有效或没有价格...

有什么办法优化吗?我在表中添加了一个索引,但仍然很慢。

【问题讨论】:

  • 你分析过EXPLAIN的查询吗?

标签: laravel laravel-5 laravel-4 eloquent laravel-5.2


【解决方案1】:

我建议使用Laravel's database query builder 代替 ORM,并在子查询中选择类似 1 而不是全部 (*) 的内容。试试这个:

DB::table('products')
    ->whereExists(function ($query) {
        $query->select(DB::raw(1))
            ->from('product_saves')
            ->whereRaw('products.id = product_saves.product_id AND user_id = 2');
    })
->get();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 2018-05-27
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多