简体   繁体   中英

Apply ORDER BY to UNION MYSQL

I'm trying to use the ORDER BY expression in my combination of UNION 's and am receiving the error

"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;

The correct syntax is

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

Edit

You're also missing an alias for the count and for the outer query. The final query should look like this

That was enough for me to set up a working example on 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;

There is a much easier solution though, that you can use since the arguments have all the same length:

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;

You can see that in action in the same rextester I linked above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM