我有2个表,我想要替换Table1中的行,其中Customer值是重复的(例如,B),其中Table2中的一行具有相同的Customer。
表1:
Customer cod
A 2
B 1
B N/A
C 5
表2:
Customer cod
B 123
所以结果应该是:
Customer cod
A 2
B 123
C 5
代码可以是:
INSERT INTO Table1
SELECT *
FROM Table2, Table1
WHERE Table1.Customer = Table2.Customer;
答案 0 :(得分:0)
首先从table2插入所需数据
INSERT INTO Table1
SELECT *
FROM Table2 t21
WHERE (SELECT count(*)
FROM Table1 t12
WHERE t12.Customer=t21.Customer) > 1;
然后从表1中删除与表2中的cod不匹配的重复项
DELETE
FROM Table1 t11
WHERE ((SELECT count(*)
FROM Table1 t12
WHERE t11.Customer = t12.Customer)>1
AND NOT cod IN (SELECT cod
FROM Table2 t21
WHERE t11.Customer=t21.Customer))
OR t11.cod IS NULL;