GROUP BY子句的别名?

时间:2011-11-29 14:37:00

标签: mysql sql

在MySQL中,可以在SELECT子句(Cf。MySQL Reference)中创建的GROUP BY子句中使用别名。

我只是想知道为什么不能在GROUP BY中创建别名并在SELECT中使用它,后者遵循SELECT语句的执行顺序。

换句话说,为什么以下不合语法?

SELECT region, SUM(population)
  FROM population_us_states
 GROUP BY
       CASE state_name
               WHEN 'CT' THEN 'New England'
               WHEN 'RI' THEN 'New England'
               WHEN 'MA' THEN 'New England'
               WHEN 'ME' THEN 'New England'
               WHEN 'NH' THEN 'New England'
               WHEN 'VT' THEN 'New England'
               WHEN 'CA' THEN 'West Coast'
               WHEN 'OR' THEN 'West Coast'
               WHEN 'WA' THEN 'West Coast'
        ELSE 'other' END AS region;

3 个答案:

答案 0 :(得分:4)

使用嵌套SELECT - 内部GROUP BY来提取总体并生成计算列,然后外部可以SELECT region, SUM(population) FROM ( SELECT CASE ... ... AS region, population FROM population_us_states ) GROUP BY region 该列:

{{1}}

答案 1 :(得分:1)

这是因为group by引用了main子句,而不是相反(或者两者兼而有之 - 两者之间的关系不是递归的)。

您可以在MySQL中执行此操作而不使用子查询,但您必须按主选择中声明的值进行分组 - 因此您的初始查询无效,但以下内容应为:

SELECT CASE state_name
               WHEN 'CT' THEN 'New England'
               WHEN 'RI' THEN 'New England'
               WHEN 'MA' THEN 'New England'
               WHEN 'ME' THEN 'New England'
               WHEN 'NH' THEN 'New England'
               WHEN 'VT' THEN 'New England'
               WHEN 'CA' THEN 'West Coast'
               WHEN 'OR' THEN 'West Coast'
               WHEN 'WA' THEN 'West Coast'
        ELSE 'other' END AS region,
        SUM(population)
  FROM population_us_states
 GROUP BY
       region;

答案 2 :(得分:0)

您的别名应包含单引号或双引号,这样MySQL才能正常工作

SELECT CASE state_name
               WHEN 'CT' THEN 'New England'
               WHEN 'RI' THEN 'New England'
               WHEN 'MA' THEN 'New England'
               WHEN 'ME' THEN 'New England'
               WHEN 'NH' THEN 'New England'
               WHEN 'VT' THEN 'New England'
               WHEN 'CA' THEN 'West Coast'
               WHEN 'OR' THEN 'West Coast'
               WHEN 'WA' THEN 'West Coast'
        ELSE 'other' END AS 'region',
        SUM(population)
  FROM population_us_states
 GROUP BY
       'region';