将ORDER BY应用于UNION MYSQL

时间:2017-06-01 08:30:18

标签: mysql sql join sql-order-by union

我正在尝试在ORDER BY的组合中使用UNION表达式并收到错误

  

“ORDER BY的表达式#1包含聚合函数并适用于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;

1 个答案:

答案 0 :(得分:0)

正确的语法是

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中看到