mysql 当 UNION 显示 [Err] 1111 - 组函数的无效使用

标签 mysql

我在 hackerrank 上做了一个 sql oj。我需要首先对人员进行排序,并列出姓名和职业以及相应的数量。数据库表像png图片显示table structure 。 我想使用

select type from
(
(
SELECT name as type, 1 as filter FROM occupations
order by name
)
UNION All
(
select concat(count(occupation), ' ', lower(occupation), 's.') as type, 2 as filter
FROM occupations
group by occupation 
order by count(occupation)
)
) result
order by filter, type

解决这个问题,但是得到“[Err] 1111 - Invalid use of group function”。 如果我按计数(职业)评论顺序可能没问题。或者只是使用

select concat(count(occupation), ' ', lower(occupation), 's.') as type, 2 as filter
FROM occupations
group by occupation 
order by count(occupation)

也可以,但是一旦union就会收到这个错误

(
SELECT name as type, 1 as filter FROM occupations
order by name
)
UNION All

(
select concat(count(occupation), ' ', lower(occupation), 's.') as type, 2 as filter
FROM occupations
group by occupation 
order by count(occupation)
)    

但是我把这个联合复制到postgresql(更改字符串契约函数)就可以了,没有这个错误。 postgresql is okay 在mysql中,我必须将这个“order by count(ocupation)”设置转换为另一个临时表来解决这个错误,如下所示:

select type from 
(
    (SELECT concat(name, '(', LEFT(occupation , 1), ')') as type, 1 as filter FROM occupations
    order by name)
UNION All
    (select * from 
        (
        select concat('There are a total of ', count(occupation), ' ', lower(occupation), 's.') as type, 2 as filter
        FROM occupations
        group by occupation 
        order by count(occupation)
        ) 
    result)
) last 
order by filter, type

我很困惑,非常感谢您的帮助!

最佳答案

order by 在联合内无效。将 order by 移到联合运算之外。

关于mysql 当 UNION 显示 [Err] 1111 - 组函数的无效使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50653049/

相关文章:

php - 选择行数时,如何选择百分比的百分比?

android - MIT App Inventor 创建多个设备可以访问的数据库

mysql - 使用 MySQL 将一个值插入到单个表中 n 次

php - mysql查询2个表并计数

php - 在 PHP 中使用数组代替大量数据库查询

php - 使用 Laravel 和 Eloquent 查询创建可过滤列表

mysql - MySQL是否支持表继承?

javascript - 使用 javascript/php 更新查询值

php - 计算mysql中的行数?

c# - 如何在插入失败时获取冲突行的主键?