获取#1111 - 无效使用组功能错误

时间:2012-08-16 08:28:16

标签: mysql group-by aggregate-functions

我看到最后一行有错误。有人可以告诉我有什么替代方案吗?

INSERT INTO month_week_qty 
(
    site_id, cat_id, cat_name, scat_id, scat_name, sscat_id, sscat_name, duration, w_m, year, sum_qty
) 
SELECT 
    c.site_id, NULL, NULL, NULL, NULL, NULL, NULL, 'month', MONTH(s.created_at), YEAR(s.created_at), ROUND( SUM( s.qty_ordered ) ) as qty 
FROM cat_products c, sku_qty_brand s
WHERE (c.product_id = s.product_id)
GROUP BY c.site_id, MONTH(s.created_at)
ON DUPLICATE KEY UPDATE sum_qty = sum_qty + ROUND( SUM( s.qty_ordered ) )

1 个答案:

答案 0 :(得分:4)

您不能在ON DUPLICATE KEY UPDATE子句中使用聚合,但您可以将分组聚合放在子查询中:

INSERT INTO month_week_qty 
(
    site_id, duration, w_m, year, sum_qty
) 
SELECT 
    site_id, duration, w_m, year, qty
FROM (
    SELECT 
        c.site_id, 'month' AS duration, MONTH(s.created_at) AS w_m, YEAR(s.created_at) AS year, ROUND( SUM( s.qty_ordered ) ) as qty 
    FROM cat_products c, sku_qty_brand s
    WHERE (c.product_id = s.product_id)
    GROUP BY c.site_id, MONTH(s.created_at)
) AS t
ON DUPLICATE KEY UPDATE sum_qty = sum_qty + t.qty

(为清楚起见,我省略了NULL列。)