Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY after ORDER BY

I need to do GROUP BY after ORDER BY. I don't understand why MySQL doesn't support that. 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 need only the first result and I need to save in a view. I can't use a SUBQUERY because of that.

The result need to be:

id | id_language | ...
1    3
2    3

Note: Don't get confused by id_language = 3, because it isn't a rule.

like image 665
David Rodrigues Avatar asked Sep 05 '11 16:09

David Rodrigues


2 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
like image 164
BitMaese Avatar answered Oct 23 '22 22:10

BitMaese


Group By will group result sets, and is generally used for aggregation. Order By is the way that results are sorted.

like image 1
Jonathan Weatherhead Avatar answered Oct 23 '22 22:10

Jonathan Weatherhead