我正在尝试按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语句部分,它可以正常工作。为什么会抛出这个错误?
答案 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);
答案 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