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

"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分组的所有披萨(应返回唯一的pizza + toppings)。但是当然这是无效的,因为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


这是正确的方法吗?还有其他选择吗?

最佳答案

是的,如果您要进行两次聚合,这是执行此操作的正确方法,除了在子查询中执行第一次聚合,没有其他选择。

但是,您没有任何聚合,因此可以使用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

关于mysql - Mysql-“group by group_concat()”的可能解决方案?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21673706/

10-12 04:42