在VALUE SELECT语句中插入GROUP BY - ERROR 1111(HY000):组功能的使用无效

时间:2017-01-07 15:42:34

标签: mysql sql group-by sql-insert insert-into

我正在尝试按ID分组后计算不同的值,然后使用以下查询将它们插入到另一个表中:

INSERT INTO table_aggregate
  (id_aggregate, aggregate_column)
(SELECT id_detail, COUNT(DISTINCT(detail_column))
  FROM table_detail
  GROUP BY id_detail)
ON DUPLICATE KEY UPDATE
  aggregate_column = COUNT(DISTINCT(detail_column));

运行时我收到错误:

  

ERROR 1111(HY000):无效使用群组功能

如果我运行查询的SELECT语句部分,它可以正常工作。为什么会抛出这个错误?

2 个答案:

答案 0 :(得分:2)

您无法在UPDATE部分中使用COUNT。请改用VALUES(aggregate_column)

INSERT INTO table_aggregate
  (id_aggregate, aggregate_column)
(SELECT id_detail, COUNT(DISTINCT(detail_column))
  FROM table_detail
  GROUP BY id_detail)
ON DUPLICATE KEY UPDATE
  aggregate_column = VALUES(aggregate_column);

http://rextester.com/KTEDM89215

答案 1 :(得分:1)

您可以将聚合放在子查询中。然后,您可以参考update

中的计算值
INSERT INTO
    table_aggregate (id_aggregate, aggregate_column) 
    SELECT
        * 
    FROM
        (
            SELECT
                id_detail,
                COUNT(DISTINCT(detail_column)) AS count 
            FROM
                table_detail 
            GROUP BY
                id_detail 
        ) AS aggr 
ON DUPLICATE KEY 
UPDATE
    aggregate_column = aggr.count