【问题标题】:mysql when UNION display [Err] 1111 - Invalid use of group functionmysql 当 UNION 显示 [Err] 1111 - 组函数使用无效
【发布时间】:2018-06-02 02:42:14
【问题描述】:

我在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)

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

(
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)
)    

但是我把这个 union 复制到 postgresql(change string contract function) 没问题,没有这个错误。postgresql is okay 在mysql中,我必须将这个“order by count(occupation)”设置转换为另一个临时表来解决这个错误,像这样:

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

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

【问题讨论】:

    标签: mysql


    【解决方案1】:

    order by 在联合中无效。将 order by 移到联合操作之外。

    【讨论】:

    • 但是为什么在 unions 中 order by name 是可以的,但是 order by count(occupation) 会导致错误,即使 order 没有意义,union 会重新排序 table
    猜你喜欢
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 2021-11-21
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多