【问题标题】:Fastest way to find count of selected items in MySql?在 MySql 中查找所选项目数量的最快方法?
【发布时间】:2016-11-14 14:28:24
【问题描述】:

我知道如何找到 COUNT,AVG 函数有效我想要实现的这里是找到计数后的另一个操作,请参阅下面的代码。

Article::where('id','=',130)
            ->select(
                'articles.*',
                DB::raw('(SELECT avg(rating) FROM rating WHERE rateable_id = articles.id AND type = "article"  ) as avgRating'),
                DB::raw('(SELECT count(*) FROM comments WHERE commentable_id = articles.id AND commentable_type = "article") as commentCount'),
                DB::raw('(SELECT count(*) FROM article_favourites WHERE article_id = articles.id ) as favouriteCount')
            )
            ->get();

使用上面的查询,我可以得到'avgRating'、'commentCount'、'favouriteCount',但我也想得到这三个的总和......即类似于:

(avgRating + commentCount + favouriteCount) AS Sum

最好的方法是什么? PS:我已经有办法了

DB::raw('( (SELECT avg(rating) FROM rating WHERE rateable_id = article.id AND type = "article")+(SELECT count(*) FROM comments WHERE commentable_id = article.id AND commentable_type = "'.$type.'")+(SELECT count(*) FROM article_favourites WHERE article_id = article.id) ) as totalCount'),

但我正在寻找更好的解决方案

【问题讨论】:

  • 恕我直言,您想多了,只需将它们添加到 php.ini 中即可。在 MySQL 中,您必须重复子查询并将它们添加为查询中的第四个表达式。
  • 我需要用总结果值对 50000 行进行排序。那怎么样?
  • 那你可能要使用fluent。
  • @Shadow 是对的。与您的解决方案相比,在 php 中求和会更快。
  • 所以你要我获取 50000 行然后总结单独的计数,然后排序(使用 totalCount)并使用数组块对行进行分页?

标签: mysql sql laravel laravel-4 count


【解决方案1】:

考虑到您的评论大约有 50,000 行。我认为这里最好注意的是索引。只要commentable_idrateable_idarticle_id被索引(当然假设articles.id是主键),你应该相对得到一个快速的查询。

在简化方面,最易读的代码(同样会更慢)是使用关系或连接与流利的结合来查找计数。即类似

$articles->comments()->count()

此外,如果您要处理可能增长到数百万行的大数据,并且需要执行排序等功能,那么使用汇总表会好得多。或者您可以添加commentCountavgRatingfavoriteCount 等字段。运行这些聚合并一直使用它对数据进行排序的开销实在是太大了。

【讨论】:

    猜你喜欢
    • 2011-01-05
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 2023-03-17
    • 2022-01-05
    相关资源
    最近更新 更多