GROUP BY after order

I need to do GROUP BY after ORDER BY . I do not understand why MySQL does not support this. This is my code:

 SELECT `pages`.`id`, `contents`.`id_language`, [...] [...] ORDER BY FIND_IN_SET(`languages`.`id`, '3') DESC [the GROUP BY] 

The results will be something like this:

 id | id_language | ... 1 3 1 1 2 3 2 5 2 1 

I need to group by ID, I only need the first result, and I need to save it as. Because of this, I cannot use SUBQUERY.

The result should be:

 id | id_language | ... 1 3 2 3 

Note. Do not confuse id_language = 3 , because this is not a rule.

+8
mysql sql-order-by group-by
source share
4 answers
 SELECT id, idl FROM (SELECT `pages`.`id` as id, `contents`.`id_language` as idl, [...] [...] ORDER BY FIND_IN_SET(`languages`.`id`, '3') DESC ) d GROUP BY d.id 
+7
source share

The By group will group the result sets and is usually used for aggregation. Order By - a way to sort the results.

+1
source share

You may need an additional column in the original query in which you are GROUP BY, as well as everything that you are grouping right now. Then this column, when grouped, can be used for subsequent ordering. For example:

 SELECT SUM(IF(`languages`.`id` = 3, 1, 0)) AS languageOrder, `pages`.`id`, `contents`.`id_language`, [...] [...] [GROUP BY...] ORDER BY languageOrder DESC 

I would like theOrder language to be positive for groups that contain language # 3, 0 otherwise. Therefore, groups containing language 3 will be located at the top.

+1
source share

Very funny try

 select * from your_table where id_language=3 order by id; 

As far as I can tell, id_language=3 rule set
which are no different than using where

0
source share

All Articles