GROUP BY after ORDER BY

与世无争的帅哥 提交于 2019-12-08 17:06:27

问题


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.


回答1:


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



回答2:


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




回答3:


You may want an additional column in your original query that you GROUP BY, along with whatever you're currently grouping by. That column, when grouped, could then be used to order afterward. For instance:

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

[...]

[GROUP BY...]

ORDER BY languageOrder DESC

I would intend for languageOrder to be positive for groups that contain language #3, 0 otherwise. So groups that contain language 3 will be at the top.




回答4:


Very amusing, try

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

As far I can tell, the rule set is id_language=3,
which make no differences from using where



来源:https://stackoverflow.com/questions/7310653/group-by-after-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!