INSERT with GROUP BY in VALUE SELECT 语句 - 错误 1111 (HY000):组函数的使用无效

INSERT with GROUP BY in VALUE SELECT Statement - ERROR 1111 (HY000): Invalid use of group function

我试图在按 id 分组后计算不同的值,然后使用以下查询将它们插入另一个 table:

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): Invalid use of group function

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

您不能在 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

您可以将聚合放在子查询中。然后你可以参考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