I want Distinct value from a column and orderby another column from a mysql database. mysql table has following data
_________________________
|id |publisher_id |view |
|1 |1 |6 |
|2 |4 |4 |
|3 |1 |3 |
|4 |3 |2 |
|5 |4 |3 |
|6 |2 |1 |
|7 |3 |7 |
|8 |5 |9 |
-------------------------
I want output as follow
_________________________
|id |publisher_id |view |
|8 |5 |9 |
|7 |2 |7 |
|1 |1 |6 |
|2 |4 |4 |
-------------------------
Laravel Query
Feed::query()->select('publisher_id', 'view')->distinct()->orderBy('view', 'DESC')->limit(4)->get();
Based on the suggestion of eckes
$feeds = \App\Models\Feed::select('publisher_id', \Illuminate\Support\Facades\DB::raw('MAX(view) as view'))
->orderBy('view', 'DESC')
->groupBy('publisher_id')
->get();
You cannot use DISTINCT
here, because DISTINCT
is applied on whole row.
You can distinct on any column,like
Feed::query()->select('publisher_id', 'view')->distinct('publisher_id')->orderBy('view', 'DESC')->limit(4)->get();
Distinct and order both are different and it does not effect on each other.
Or you can use group by instead of Distinct, like
Feed::query()->select('publisher_id', 'view')->groupBy('publisher_id')->orderBy('view', 'DESC')->limit(4)->get();