gpt4 book ai didi

mysql - 将 ORDER BY 应用于 UNION MYSQL

转载 作者:行者123 更新时间:2023-11-29 18:52:51 26 4
gpt4 key购买 nike

我尝试在 UNION 组合中使用 ORDER BY 表达式,但收到错误

"Expression #1 of ORDER BY contains aggregate function and applies to a UNION".

(SELECT 'SELECT' AS argument, count(argument) FROM mysql.general_log WHERE 
argument LIKE ("SELECT%"))
UNION
(SELECT 'INSERT' AS argument, count(argument) FROM mysql.general_log WHERE
argument LIKE ("INSERT%"))
UNION
(SELECT 'UPDATE' AS argument, count(argument) FROM mysql.general_log WHERE
argument LIKE ("UPDATE%"))
UNION
(SELECT 'DELETE' AS argument, count(argument) FROM mysql.general_log WHERE
argument LIKE ("DELETE%"))
ORDER BY count(argument) ASC;

最佳答案

正确的语法是

select * from
( query 1 union query 2 union query 3...)
order by x

编辑

您还缺少计数和外部查询的别名。最终查询应如下所示

这足以让我在 rextester 上设置一个工作示例.

SELECT argument, cnt from
(
(SELECT 'SELECT' AS argument, count(argument) as CNT FROM mysql.general_log WHERE
argument LIKE ("SELECT%"))
UNION
(SELECT 'INSERT' AS argument, count(argument) FROM mysql.general_log WHERE
argument LIKE ("INSERT%"))
UNION
(SELECT 'UPDATE' AS argument, count(argument) FROM mysql.general_log WHERE
argument LIKE ("UPDATE%"))
UNION
(SELECT 'DELETE' AS argument, count(argument) FROM mysql.general_log WHERE
argument LIKE ("DELETE%"))
) aa
ORDER BY cnt ASC;

不过,您可以使用一个更简单的解决方案,因为参数的长度都相同:

select  substring(upper(argument), 1, 6) as argument, count(*) as cnt
from mysql.general_log
group by substring(upper(argument), 1, 6)
order by cnt asc;

您可以在我上面链接的同一个 rextester 中看到它的作用

关于mysql - 将 ORDER BY 应用于 UNION MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44302363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com