2016-05-22 117 views
2

我想用where子句將三個表連接起來。在第一個示例 中,查詢結果爲內部聯接。如果我刪除where子句,則會導致左連接,但會包含所需日期範圍之外的記錄。WHERE子句使得LEFT JOIN像INNER JOIN一樣工作

我使用Microsoft Access 2010和Visual Basic 2010

strQry = " SELECT tblUnits.UnitNumber, TenantName, SchedRent, SchedCAM, sum(AMOUNT) as SUMAMOUNT " _ 
    & " FROM ((tblUnits LEFT JOIN tblTenants ON tblTenants.Unitptr = tblUnits.ID) " _ 
    & " LEFT JOIN tblTrans ON (tblTenants.ID = tblTrans.id) ) " _ 
    & " WHERE (tblTrans.PostDate BETWEEN #" & txtStartDate.Text & "# AND #" & txtEndDate.Text & "#) " _ 
    & " GROUP BY tblUnits.UnitNumber, TenantName, SchedRent, SchedCAM " _ 
    & " ORDER BY tblUnits.UnitNumber " 

在它完美的第二個例子,但只連接兩個表

strQry = " SELECT U.UnitNumber, sum(AMOUNT) as sumamount " _ 
& " FROM tblUnits AS U " _ 
    & " LEFT JOIN " _ 
    & " (" _ 
    & " SELECT * " _ 
    & " FROM tblTrans " _ 
    & " WHERE (tblTrans.PostDate BETWEEN #" & txtStartDate.Text & "# AND #"  & txtEndDate.Text & "#) " _ 
    & ") as X " _ 
    & " ON U.ID = X.ID " _ 
    & " GROUP BY U.UnitNumber " 

我不能讓語法當我嘗試加入第三張表格時正確

+1

在列表來查詢。不要讓我們讀= =。它使發佈答案更加困難。我通過。 – Paparazzi

回答

0

嘗試WHERE tblTrans.PostDate IS NULL OR ...

就目前而言,您的LEFT JOIN包含沒有匹配的tblTrans行的tblUnits行。然後你的WHERE子句消除這些行。

+0

訪問允許在ON子句中使用「或」而不是「AND」 – Larrythebruin

+0

@Larrythebruin好的,我已經刪除了該替代 – Joe

0

以下工作

strQry = " SELECT U.UnitNumber, T.TenantName, T.SchedRent, T.SchedCAM, sum(AMOUNT) as SUMAMOUNT " _ 
     & " FROM ((tblUnits AS U " _ 
     & " LEFT JOIN tblTenants as T ON U.ID = T.UnitPtr) " _ 
     & " LEFT JOIN " _ 
     & " (" _ 
     & " SELECT * " _ 
     & " FROM tblTrans " _ 
     & " WHERE (tblTrans.PostDate BETWEEN #" & txtStartDate.Text & "# AND #" & txtEndDate.Text & "#) " _ 
     & ") as X " _ 
     & " ON U.ID = X.ID) " _ 
     & " GROUP BY U.UnitNumber, TenantName, SchedRent, SchedCAM " _ 
     & " ORDER BY U.UnitNumber "