mysqli query order by before group by

Solutions on MaxInterview for mysqli query order by before group by by the best coders in the world

showing results for - "mysqli query order by before group by"
Colin
04 Apr 2017
1//it is very difficult to find a query that uses Order By before Group By
2//so, below is the query when you want to first order the results in Asc (min) or Desc (max) order, and then Group by
3$raw_query = 'SELECT p1.* FROM table1 p1
4         INNER JOIN ( SELECT max(firstValue) MaxAnyId, secondValue
5                            FROM table1
6                            WHERE user_id=162
7                               AND status_id=70
8                            GROUP BY secondValue
9                        ) p2
10                          ON p1.secondValue = p2.secondValue
11                          AND p1.firstValue = p2.MaxLogId
12                        WHERE p1.user_id=162
13                          AND p1.status_id=70
14                        order by p1.firstValue desc';
15                        
16//for Laravel ->                        
17$q = \DB::select($raw_query);