INSERT SELECT ON DUPLICATE UPDATE的SQL语法

时间:2012-01-31 18:24:34

标签: mysql sql

我想要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?

1 个答案:

答案 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