【问题标题】:Laravel orderBy slowing down response greatlyLaravel order通过大大减慢响应
【发布时间】:2017-08-20 17:06:49
【问题描述】:

省略不必要的信息,表结构如下(没有列出所有的with关系):

products
  id
  launch_date
  name

product_view_history
  id
  account_id
  product_id
  timestamps

我的查询花费了不规则的长时间。通过我所做的所有分析,在 SQL 中花费的实际时间非常少(<50 ms),但执行此代码所需的时间在900+ms 范围内:

$this->select('products.*', DB::raw('COUNT(product_view_history.id) as view_count'))
     ->leftJoin('product_view_history', 'product_view_history.product_id', '=', 'products.id', 'outer')
     ->groupBy('product_view_history.product_id')
     ->orderBy('view_count', 'DESC')
     ->orderBy('products.id', 'DESC')
     ->whereNotNull('products.launch_date')
     ->with(['owner.images', 'owner.star', 'owner.follows', 'owner.followers', 'company.products.alphas'])
     ->take(Config::get('xxxx.limits.small'))
     ->get();

但是,如果我注释掉 ->orderBy('view_count', 'DESC'),则执行此代码所需的时间会减少到适当的 <50ms。如果我将get() 换成toSql() 并手动运行这两个查询,我会发现时间相对相似且较小。要明确衡量所花费的时间不是 SQL 查询时间;我只是在完成此操作之前和之后直接获取时间(以毫秒为单位)并记录差异。

任何人都知道为什么->orderBy('view_count', 'DESC') 会为代码的执行增加将近一秒的时间,即使 SQL 本身并没有/最低限度地慢?

【问题讨论】:

  • 您是否尝试在 DB:raw 查询中使用 toSql 来检查它是否只是 Eloquent 查询构建器的问题?
  • Eloquent 为了方便而牺牲了速度。
  • 但是这个 orderBy 会导致这么慢。

标签: mysql laravel eloquent mariadb


【解决方案1】:

对我来说,这是由于在 where 查询中使用了“错误”的数据类型造成的。 例如,我通过一个名为“username”的列进行过滤,该列是一个 varchar,但插入了一个 Int 作为过滤的值。 使用 orderBy 需要很长时间,但删除 orderBy 时又很快。 解决方案至少是让我将用户名转换为 String 并且 orderBy 像以前一样流畅。我不知道真正的原因,但在使用不匹配的数据类型时,Eloquent 可能会进行不同的强制转换或排序。

【讨论】:

    【解决方案2】:

    似乎执行原始查询,水合和加载似乎加快了查询速度。这没有回答为什么订购会导致这样的问题,但它确实回答了如何解决手头的问题:

    $products = self::hydrate(DB::select(
        "select `products`.*, COUNT(product_view_history.id) as view_count
        from `products` left join `product_view_history`
        on `product_view_history`.`product_id` = `products`.`id`
        where `products`.`launch_date` is not null
        group by `product_view_history`.`product_id`
        order by `view_count` desc, `products`.`id` desc limit {$limit}"))
        ->load(['owner.images', 'owner.star', 'owner.follows', 'owner.followers', 'company.products.alphas']);
    

    【讨论】:

      猜你喜欢
      • 2012-04-08
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多