查找未包含在另一个查询中的记录

时间:2012-08-10 15:04:31

标签: vba ms-access

我有两个彼此相关的表:QUOTERunQUOTERunResultsQUOTERun包含特定报价所需的所有项目。 QUOTERunResults包含所有供应商响应的记录。我有一个程序来分析这些响应并选择最适合的供应商并将名为Preffered的字段设置为true。有些时候没有供应商会工作。我需要创建一个QUOTERun中所有记录的列表,这些记录在QUOTERunResults中没有标记为优先的匹配记录。

这是我到目前为止的内容

Set rs1 = CurrentDb.OpenRecordset("SELECT ReferenceNumber FROM [QUOTERun] WHERE RunID = " & TempRunID, dbOpenDynaset)
Set rs2 = CurrentDb.OpenRecordset("SELECT ReferenceNumber, Preffered FROM [QUOTERunResults] " & _
                                  "WHERE RunID = " & TempRunID & " AND Preffered = True", dbOpenDynaset)
If (rs2.RecordCount = 0) Then
   TempListNotComplete = "NONE OF THE VENDOR RESPONSES HAD ENOUGH STOCK. NO RECORDS HAVE BEEN MARKED AS PREFFERED."
ElseIf (rs1.RecordCount <> 0) Then
   rs1.MoveFirst
   Do While rs1.EOF <> True
      rs2.FindFirst "ReferenceNumber = " & rs1.Fields("[ReferenceNumber]").value
      If (rs2.Fields("[ReferenceNumber]").value <> rs1.Fields("[ReferenceNumber]").value) Then
         If (TempListNotComplete = "") Then 
            TempListNotComplete = rs1.Fields("[ReferenceNumber]").value 
     Else 
            TempListNotComplete = TempListNotComplete & ", " & rs1.Fields("[ReferenceNumber]").value
     End If
      End If
      rs1.MoveNext
   Loop
End If

有更有效的方法来完成上述工作吗?

1 个答案:

答案 0 :(得分:3)

您可以在查询设计窗口的SQL视图中创建查询:

SELECT a.ReferenceNumber 
FROM
    (SELECT ReferenceNumber 
     FROM [QUOTERun] 
     WHERE RunID = [Enter TempRunID]) a
LEFT JOIN 
    (SELECT ReferenceNumber, Preffered 
     FROM QUOTERunResults 
     WHERE RunID = [Enter TempRunID] AND Preffered = True) b
On a.ReferenceNumber=b.ReferenceNumber
WHERE b.ReferenceNumber Is Null

上面应该显示第一个派生表中不在第二个派生表中的所有记录。