gpt4 book ai didi

mysql - 在 MySql 中查找所选项目数量的最快方法?

转载 作者:行者123 更新时间:2023-11-29 20:47:43 27 4
gpt4 key购买 nike

我知道如何找到 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'),

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

最佳答案

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

就简化而言,最易读的代码(同样会更慢)将是使用关系或连接与 Fluent 结合来查找计数。即类似于

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

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

关于mysql - 在 MySql 中查找所选项目数量的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38327313/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com