2016-07-28 170 views
0

我有兩個表:newparts,storedpartsMS訪問SQL加入子查詢

我插入newparts,這是不是在storedparts噴入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);" 

這是工作的罰款至今。現在的問題:表storedparts變得如此之大,程序對於連接過程來說太長了。我的解決方案:只是比較newparts不是存儲的部分的所有部分,但只是部分不超過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

爲什麼'RIGHT JOIN'?如果真的需要外部連接,切換表並執行'LEFT JOIN'。大多數人覺得那些人很難理解,而且加入的方式更加混亂。 (更容易理解「主表左連接可選數據」而不是「可選數據右連接主​​表」)。 – jarlh

回答

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; 
0

您可以在連接語句之後添加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);"