我有两个表(Test和Prod)并且有一个存储过程,每天运行以在Prod中不存在的Test中插入行。
目前它只是一个简单的插入,如下所示:
INSERT INTO Table1 ('Field1','Field2','Field3','Field4')
SELECT 'Field1','Field2','Field3','Field4'
FROM Table2
WHERE Table2.Field1 NOT IN (SELECT Table1.Field1 FROM Table1)
问题是这些表有很多行,这需要很长时间才能运行。是否有更好/更有效的方式来写这个?
答案 0 :(得分:1)
在两个表上的Field1上创建索引。 除此之外,我不知道如何优化它。
答案 1 :(得分:0)
您可以尝试这样的事情:
INSERT INTO Table1 (Field1, Field2, Field3, Field4)
SELECT t2.Field1, t2.Field2, t2.Field3, t2.Field4
FROM Table2 t2
LEFT JOIN Table1 t1 ON (t1.Field1 = t2.Field1)
WHERE t1.Field1 IS NULL;
答案 2 :(得分:0)
INSERT INTO Table1 ('Field1','Field2','Field3','Field4')
SELECT 'Field1','Field2','Field3','Field4'
FROM Table2 t2
WHERE NOT EXISTS (SELECT t1.Field1 FROM Table1 t1 WHERE t1.Field1 = t2.Field1)