为什么ORDER BY在这种情况下不起作用?

时间:2016-11-09 21:09:24

标签: mysql sql

我想打印一些统计数据,所以我有以下代码:

(SELECT 'There are total', COUNT(Name), 'doctors.' FROM OCCUPATIONS
WHERE Occupation = 'Doctor')
UNION
(SELECT 'There are total', COUNT(Name), 'singers.' FROM OCCUPATIONS
WHERE Occupation = 'Singer')
UNION
(SELECT 'There are total', COUNT(Name), 'actors.' FROM OCCUPATIONS
WHERE Occupation = 'Actor')
UNION
(SELECT 'There are total', COUNT(Name), 'professors.' FROM OCCUPATIONS
WHERE Occupation = 'Professor')
ORDER BY COUNT(Occupation);

计算每个职业的发生次数。我还需要根据事件对每个职业对应的这4行进行排序。我的代码似乎不起作用:

ERROR 1054 (42S22) at line 4: Unknown column 'Occupation' in 'order clause' 

有什么问题以及如何解决?

2 个答案:

答案 0 :(得分:3)

您需要别名COUNT(Name)并在ORDER BY中使用该别名:

(SELECT 'There are total', COUNT(Name) OccupationCount, 'doctors.' FROM OCCUPATIONS
WHERE Occupation = 'Doctor')
UNION
(SELECT 'There are total', COUNT(Name), 'singers.' FROM OCCUPATIONS
WHERE Occupation = 'Singer')
UNION
(SELECT 'There are total', COUNT(Name), 'actors.' FROM OCCUPATIONS
WHERE Occupation = 'Actor')
UNION
(SELECT 'There are total', COUNT(Name), 'professors.' FROM OCCUPATIONS
WHERE Occupation = 'Professor')
ORDER BY OccupationCount;

但是,您不必使用UNION。您可以轻松地将COUNTGROUP BYWHERE子句一起使用:

SELECT
    'There are total',
    COUNT(Name) OccupationCount,
    CONCAT(LOWER(Occupation), 's')
FROM OCCUPATIONS
WHERE Occupation IN('Doctor', 'Singer', 'Actor', 'Professor')
GROUP BY Occupation
ORDER BY OccupationCount;

答案 1 :(得分:1)

您可以使用列号而不是表达式来执行此操作:

 ORDER BY 2

...将按第二列排序。

Count(Occupations)不会出现在select列表中,或者在其他方面可用。我假设您打算对每个子查询中的Count(name)进行排序。