group by、order by 先后顺序问题

时间:2023-01-22 14:25:20

今天遇到个小问题 本来是很基础的问题 应该说 基础知道掌握的不牢  好了不说

错误 语句 :   select  a.a1  from table a  where order by a.a1 group by a1

正确的语句是: select  a.a1  from table a  where  group by a1 order by a.a1

原因 :group by 比order by先执行,order by不会对group by 内部进行排序

虽然 SELECT 语句的完整语法较复杂,但是其主要的子句可归纳如下:
  SELECT select_list
  [ INTO new_table ]
  FROM table_source
  [ WHERE search_condition ]
  [ GROUP BY group_by_expression ]
  [ HAVING search_condition ]
  [ ORDER BY order_expression [ ASC | DESC ] ]