2017-06-01 70 views
0

我試圖用我的UNION的組合ORDER BY表達,我收到錯誤ORDER BY的應用ORDER BY到UNION MYSQL

「表達式#1包含聚合函數,並適用於聯盟」。

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

回答

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
+0

嗨,我迎接錯誤「每個派生表必須有它自己的別名」 – Sailthor

+0

感謝,但類似的錯誤「ORDER BY的表達式1包含聚合函數並適用於非聚合查詢的結果」 – Sailthor

+0

這樣做工作,非常感謝。爲什麼MySql要求我們使用這個別名? – Sailthor