我在以下查询中收到错误
INSERT INTO tableName3 (column1, column2)
SELECT
b.column1,
SUM (a.column2) AS SumColumn2
FROM
tableName1 AS a
JOIN
tableName2 AS b ON a.column1 = b.column2
GROUP BY
b.column2
ON DUPLICATE KEY UPDATE tableName3
SET column2 = SUM (a.column2) AS SumColumn2
错误消息是
关键字' ON *'
附近的语法不正确
和
关键字' AS'
附近的语法不正确
如何解决?
答案 0 :(得分:2)
首先,你的select语句错误。
SELECT
b.column1,
SUM (a.column2) AS SumColumn2
FROM
tableName1 AS a
JOIN
tableName2 AS b ON a.column1 = b.column2
GROUP BY
b.column2
这应该按b.column1
分组,否则你会得到一个例外,因为select子句中的列必须出现在group by子句中或sql-server中的聚合函数中
第二,Sql server中没有ON DUPLICATE KEY
指令。快速搜索在mysql中找到了许多参考文献,但mysql 不是 sql-server。
要在Sql server中实现这种行为,您应该使用MERGE
语句。
您的代码应如下所示:
MERGE tableName3 AS target
USING (
SELECT
b.column1,
SUM (a.column2) AS SumColumn2
FROM
tableName1 AS a
JOIN
tableName2 AS b ON a.column1 = b.column2
GROUP BY
b.column1
) AS source (column1, SumColumn2)
ON (target.column1= source.column1)
WHEN MATCHED THEN
UPDATE SET column2= source.SumColumn2
WHEN NOT MATCHED THEN
INSERT (column1, column2)
VALUES (source.column1, source.SumColumn2)