我想要GROUP并聚合一个表中的行并插入另一个表中,并更新聚合值。什么是SQL命令?
INSERT INTO tbdetail (detail, views)
(SELECT detail, SUM(views) AS viewsall
FROM tb
GROUP BY detail)
//ON DUPLICATE KEY UPDATE views = views + viewsall <- how to update here?
答案 0 :(得分:3)
在MySQL中,当使用INSERT ... SELECT
语句时,您可以使用SELECT
函数引用VALUES()
语句的其中一个值:
INSERT INTO tbdetail (detail, views)
SELECT detail, SUM(views) AS viewsall FROM tb GROUP BY detail
ON DUPLICATE KEY UPDATE views = views + VALUES(views);
此处提供更多信息:http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_values