- Talk about those hidden secrets! ! !
laravel framework to write the number of users of statistics collection, we intend to use the groupBy + COUNT is achieved (+ deduplication statistics), plus the groupBy again after COUNT , count out the number does not of. + Query data has finally been repeatedly tested solutions.
Wrong query ❌
Model::whereIn('course_id',$course_ids)->groupBy('uid')->count();
After groupBy by packet, then performing Count () function returns: the data packet, the number of the first packet.
Correct query ✔️
Model::whereIn('course_id',$course_ids)->groupBy('uid')->get()->count();
// 或
Model::whereIn('course_id',$course_ids)->count(DB::raw('DISTINCT(uid)')));
// 或
conut(Model::whereIn('course_id',$course_ids)->groupBy('uid')->pluck('uid')->toArray());
distinct keywords
The default MySQL query are displayed for all rows, including duplicate rows.
SELECT clause in MySQL DISTINCT keyword to eliminate duplicate rows and displays a unique list of values.
That higher efficiency DISTINCT and GROUP BY Which?
DISTINCT operations only need to find all the different values on it. The GROUP BY operation should be prepared to work for other aggregate functions. From this point on, work GROUP BY operation than to do the job should be done to be more DISTINCT.
But in fact, GROUP BY more efficient point, why? For the DISTINCT operation, it reads all records, while as many as the number of groups and number of GROUP BY grouping records to be read, that is more than the number of records actually exist much less.
Conclusion
Share on here today, I believe we will be watching the harvest.
Let those who are hidden secrets are dug up, encourage each other!