INSERT INTO `tableA`
SELECT `Col1`,
`Col2`,
NOW()
FROM `tableB`
WHERE tableA.Col1 is not already in tableB.Col1
我无法正确使用 WHERE 子句来确保从 tableA 复制的记录只出现在表 B 中一次......
应该读:
其中 tableA.col1 不在(从表 B 中选择 col1)
您确实需要 SQL-2003 MERGE 语句。我已经从下面的标准(怪诞,但这是你的 SQL 标准)中包含了 MERGE 语句的 BNF(第 14.9 节,p837)。翻译后,可能会转化为:
MERGE INTO TableA
USING TableB ON TableA.Col1 = TableB.Col1
WHEN NOT MATCHED INSERT (Col1, Col2, Col3)
VALUES(TableB.Col1, TableB.Col2, NOW());
我没有通过一个知道 MERGE 语句的 SQL DBMS 运行它——这意味着它可能存在错误。请注意,标准中有一个 WHEN MATCHED 子句可以接受 UPDATE;IBM DB2 还支持 2003 标准中没有的 DELETE 子句(不确定 2008 标准)。
<merge statement>
(p837)有条件地更新表的行,或将新行插入表中,或两者兼而有之。
<merge statement> ::=
MERGE INTO <target table> [ [ AS ] <merge correlation name> ]
USING <table reference> ON <search condition>
<merge operation specification>
<merge correlation name> ::=
<correlation name>
<merge operation specification> ::=
<merge when clause> ...
<merge when clause> ::=
<merge when matched clause> |
<merge when not matched clause>
<merge when matched clause> ::=
WHEN MATCHED THEN <merge update specification>
<merge when not matched clause> ::=
WHEN NOT MATCHED THEN <merge insert specification>
<merge update specification> ::= UPDATE SET <set clause list>
<merge insert specification> ::=
INSERT [ <left paren> <insert column list> <right paren> ]
[ <override clause> ] VALUES <merge insert value list>
<merge insert value list> ::=
<left paren> <merge insert value element>
[ { <comma> <merge insert value element> }... ] <right paren>
<merge insert value element> ::=
<value expression> |
<contextually typed value specification>