将 ORDER BY 应用于 UNION MYSQL
Apply ORDER BY to UNION MYSQL
我试图在 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 中看到它的运行情况
我试图在 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 中看到它的运行情况