当我跑步时
SELECT concat(name,'(',substring(occupation,1,1),')')
FROM occupations
UNION ALL
SELECT concat('There are total ',count(occupation),' ', occupation,'.')
FROM occupations
GROUP BY occupation
查询工作正常,但是当我按
添加订单时SELECT concat(name,'(',substring(occupation,1,1),')')
FROM occupations
UNION ALL
SELECT concat('There are total ',count(occupation),' ', occupation,'.')
FROM occupations
GROUP BY occupation
ORDER BY name
这显示错误:
'order clause'中的未知列'name'
表职业字段名称,职业
答案 0 :(得分:3)
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
更新:为何如此:
因为您没有名为name
的公共列。将函数应用于查询时,mysql使用该函数名称和参数的组合为您创建列名。实际上,这意味着查询的名称为concat(name,'(',substring(occupation,1,1),')')
(最有可能是大写的),而第二个将有concat('There are total ',count(occupation),' ', occupation,'.')
就Union而言,名称是不同的并不重要,因为mysql足够聪明,可以通过数据类型将它们组合在一起。但是,当您添加order by子句时,您需要一个两者共有的列名。
答案 1 :(得分:3)
为您的选择列添加别名:
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
答案 2 :(得分:3)
SELECT concat(name,'(',substring(occupation,1,1),')') FROM occupations
UNION ALL SELECT concat('There are total ',count(occupation),' ', occupation,'.') FROM occupations GROUP BY occupation
ORDER BY name
在上面的查询中没有返回名为name
的列。
您可以改用它。
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
答案 3 :(得分:0)
关系数据模型依赖于关系代数。你的所有表都是关系。选择是对你的关系的一个clojure操作,也就是说,选择将关系作为输入并且具有关系作为输出。
话虽如此,让我们确定你问题中使用的关系。一切都依赖于你的occupations
关系。您正在使用该关系进行两项选择。第一个输出基于记录的文本输出,第二个输出基于operation
的分组值。您的union
不知道名称,因为它包含一个无名的列,并且该无名列与您调用的列name
不匹配。
有几位回答者提供了技术上合理的解决方案,但答案在逻辑上是不合理的。我们不应该将name
作为别名给第二个选择的无名列,因为它显然是一个数字。你需要做一些其他事情,比如:
select total
from
(SELECT concat(name,'(',substring(occupation,1,1),')') as name, 0 as total
FROM occupations
UNION ALL
SELECT name, concat('There are total ',count(occupation),' ', occupation,'.') as total
FROM occupations
GROUP BY occupation) t
order by name