【发布时间】: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