一尘不染

用于重复键更新的SQL查询插入错误

sql

我在以下查询中出错

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”附近的语法不正确

如何解决?


阅读 102

收藏
2021-05-16

共1个答案

一尘不染

首先, 您的选择语句是错误的。

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
中的聚合函数中

其次ON DUPLICATE KEYSql
server中没有指令。一个快速搜索发现,在这个许多人提到的MySQL,但MySQL的不是
SQL服务器

要在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)
2021-05-16