MS ACCESS SQL加入子查询

时间:2016-07-28 08:51:20

标签: sql access-vba database-performance right-join

我有两个表:newparts,storedparts

我将存储部件中未喷射的新部件插入到已存储的部件中:

SQL_String = "INSERT INTO storedparts " & _
             "SELECT newparts.* " & _
             "FROM storedparts " & _
             "RIGHT JOIN newparts ON (storedparts.identifier = newparts.identifier) AND (storedparts.timeStamp = newparts.timeStamp) " & _
             "WHERE ((storedparts.AutoID) Is Null);"

到目前为止,此工作正常。现在的问题:Table storedparts变得如此之大,以至于程序对于连接过程来说太长了。我的解决方案:只是将新部件与存储部件的所有部分进行比较,而不仅仅是对不超过4天的部件进行比较......我尝试了这样的子查询,但我无法运行它

SQL_String = "INSERT INTO storedparts " & _
             "SELECT newparts.* " & _
             "FROM storedparts (WHERE storedparts.timestamp > Now() - 4) " & _
             "RIGHT JOIN newparts ON (storedparts.identifier = newparts.identifier) AND (storedparts.timeStamp = newparts.timeStamp) " & _
             "WHERE ((storedparts.AutoID) Is Null);"

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您可以在join语句之后添加where子句,看看它是否提高了查询的性能。否则尝试一下,看看它是否有效

SQL_String = "INSERT INTO storedparts " & _
             "SELECT newparts.* " & _
             "FROM ( SELECT * FROM storedparts WHERE 
              storedparts.timestamp > DateAdd ( 'd', -4, Now()) )sparts" & _
             "RIGHT JOIN newparts ON (sparts.identifier = newparts.identifier) AND 
             (sparts.timeStamp = newparts.timeStamp) " & _
             "WHERE ((sparts.AutoID) Is Null);"

答案 1 :(得分:0)

如果你的表有索引,这不会有问题。

CREATE INDEX ndx_sp_identifier ON storedparts (identifier);
CREATE INDEX ndx_np_identifier ON newparts (identifier);

然后我建议你把你的查询改成像@jarlh指出的那样。

INSERT INTO storedparts 
SELECT newparts.* 
FROM newparts
LEFT JOIN storedparts 
ON newparts.identifier = storedparts.identifier
AND newparts.timeStamp = storedparts.timeStamp
WHERE storedparts.AutoID Is Null;