ORDER BY后的GROUP BY

时间:2011-09-05 16:29:42

标签: mysql group-by sql-order-by

我需要GROUP BY之后ORDER BY。我不明白为什么MySQL不支持它。 这是我的代码:

SELECT
    `pages`.`id`,
    `contents`.`id_language`,
    [...]

[...]

ORDER BY
    FIND_IN_SET(`languages`.`id`, '3') DESC

[the GROUP BY]

结果将是这样的:

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

我需要按ID分组,我只需要第一个结果,我需要保存在视图中。因此,我无法使用SUBQUERY。

结果必须是:

id | id_language | ...
1    3
2    3

注意:不要被id_language = 3弄糊涂,因为这不是一个规则。

4 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:1)

Group By将对结果集进行分组,通常用于聚合。 Order By是结果排序的方式。

答案 2 :(得分:1)

您可能需要在原始查询中添加另一列GROUP BY,以及您当前正在分组的任何列。该列在分组后可用于后续订购。例如:

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

[...]

[GROUP BY...]

ORDER BY languageOrder DESC

我打算让languageOrder对包含语言#3的组保持肯定,否则为0。因此,包含语言3的组将位于顶部。

答案 3 :(得分:0)

非常有趣,试试

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

据我所知,规则集是id_language=3
与使用where

没有区别