Mysql - “group by group_concat()”的可能解决方案?

时间:2014-02-10 09:46:22

标签: mysql sql group-by

是否可以通过聚合函数的结果对结果进行分组而不将结果嵌套在自身上?

"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 个答案:

答案 0 :(得分: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;

N.B。如果您确实需要执行聚合,则在子查询中缺少一个组,应该是:

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