2014-02-10 64 views
0

是否可以通過聚合函數的結果對結果進行分組,而不將結果嵌套在自身上?Mysql - 「group by group_concat()」的可能解決方案?

"SELECT b.pizza, GROUP_CONCAT(t.topping_names SEPARATOR ',') AS topping_string FROM bascket AS b 
LEFT JOIN toppings AS t ON t.pizza = b.pizza 
GROUP BY pizza, topping_string " 

上面的查詢將返回由他們所選擇的topping_string分組的所有比薩餅(應返回獨特的比薩澆頭+)。但是因爲group_concat是在分組之後完成的,所以這是無效的。因此,我認爲唯一的選擇將是換行查詢,並使其實際分組的子查詢:

SELECT sub.* FROM ( 
SELECT b.pizza, GROUP_CONCAT(t.topping_names SEPARATOR ',') AS topping_string FROM bascket AS b 
    LEFT JOIN toppings AS t ON t.pizza = b.pizza 
) AS sub 
GROUP BY sub.pizza, sub.topping_string 

這是正確的方式做到這一點?有另外一種選擇嗎?

回答

1

是的,如果你正在做兩個聚合,這是正確的做法,沒有辦法在子查詢中執行第一個聚合。

但是,你沒有任何的聚合,因此您可以通過使用DISTINCT強制唯一性:

SELECT DISTINCT 
     b.pizza, 
     GROUP_CONCAT(t.topping_names SEPARATOR ',') AS topping_string 
FROM bascket AS b 
    LEFT JOIN toppings AS t 
     ON t.pizza = b.pizza 
GROUP BY b.pizza; 

注:如果您確實需要執行聚合,則您在子查詢中缺少一個組,應該是:

SELECT sub.*, COUNT(*) AS Quantity FROM ( 
SELECT b.pizza, GROUP_CONCAT(t.topping_names SEPARATOR ',') AS topping_string 
FROM bascket AS b 
    LEFT JOIN toppings AS t ON t.pizza = b.pizza 
GROUP BY b.pizza 
) AS sub 
GROUP BY sub.pizza, sub.topping_string 
+0

實際查詢比較大,這只是底層問題的一個簡單示例。所以我看到,在同一個查詢中不能有基於分組結果的分組。我會接受你的回答 –

+0

是的,我在子查詢中注意到了這個組。 Ty再次尋求幫助。 –