WITH UNION ALL unable to use ORDER BY

后端 未结 4 618
栀梦
栀梦 2021-01-26 08:12

When I am running

SELECT concat(name,\'(\',substring(occupation,1,1),\')\')  
FROM  occupations    
UNION ALL 
SELECT concat(\'There are total \',count(occupati         


        
4条回答
  •  被撕碎了的回忆
    2021-01-26 08:48

    SELECT concat(name,'(',substring(occupation,1,1),')') as name
    FROM  occupations    
    UNION ALL 
    SELECT concat('There are total ',count(occupation),' ', occupation,'.') as name
    FROM occupations GROUP BY occupation 
    ORDER BY name
    

    Update: Why this is so:
    Because you don't have a common column named, name. When you apply a function to a query, mysql use a combination of that function name and parameters to create a column name for you. Which in reality means query will have a name of concat(name,'(',substring(occupation,1,1),')') (most probably upper cased) while the second will have concat('There are total ',count(occupation),' ', occupation,'.')

    It doesn't matter that the names are different as far as Union is concerned because mysql is smart enough to combine them together by their data type. However when you add an order by clause you need a column name that's common to both.

提交回复
热议问题