sql - Fastest way to find count of selected items in MySql? -
i know how find count,avg functions works want i'm trying achieve here operation after count found please see code below.
article::where('id','=',130) ->select( 'articles.*', db::raw('(select avg(rating) rating rateable_id = articles.id , type = "article" ) avgrating'), db::raw('(select count(*) comments commentable_id = articles.id , commentable_type = "article") commentcount'), db::raw('(select count(*) article_favourites article_id = articles.id ) favouritecount') ) ->get();
using above query, can 'avgrating', 'commentcount', 'favouritecount', want sum of these three.. i.e. like:
(avgrating + commentcount + favouritecount) sum
what best way this? ps: have solution
db::raw('( (select avg(rating) rating rateable_id = article.id , type = "article")+(select count(*) comments commentable_id = article.id , commentable_type = "'.$type.'")+(select count(*) article_favourites article_id = article.id) ) totalcount'),
but looking better solution
considering comment 50,000 rows. think best thing mindful of here indexes. long commentable_id
, rateable_id
, article_id
indexed (assuming of course articles.id
primary key), should relatively fast query.
in terms of simplification, readable code (which likewise slower) use relations or joins in conjunction fluent find count. i.e. like
$articles->comments()->count()
in addition, if you're dealing large data may grow millions of rows , need perform function sorting, you're far better off summary table. or may add fields commentcount
, avgrating
, favoritecount
. overhead of running these aggregates , using sort data time much.
Comments
Post a Comment