WHERE子句使LEFT JOIN像INNER JOIN一样工作

时间:2016-05-22 19:37:18

标签: vb.net ms-access-2010

我试图用where子句连接三个表。在第一个例子中 查询导致内部联接。如果我取出where子句,则会产生左连接,但是包含所需日期范围之外的记录。

我正在使用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 "

当我尝试加入第三个表时,我无法正确理解语法

2 个答案:

答案 0 :(得分:0)

尝试WHERE tblTrans.PostDate IS NULL OR ...

就目前而言,您的LEFT JOIN包含tblUnits行,其中没有匹配的tblTrans行。然后你的WHERE子句消除了这些行。

答案 1 :(得分: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 "