SQL 哪里有 Union 和 Left

SQL where with Union and Left

是否可以在 Left Join 的 [ID] 而不是 [TypeID] 中添加条件?

 SQL = "SELECT " & _
          "ADate As NewDate, " & _
          "tblA.TypeID as ID, " & _
          "tblAB.TypeControl as ControlID " & _
          "FROM tblA " & _
               "LEFT OUTER JOIN tblAB " & _
               "ON tblAB.TypeID = tblA.TypeID " & _
               "WHERE tblA.TypeID = " & Counter & " " & _     => Delete this one.
       "UNION ALL SELECT " & _
          "BDate As NewDate, " & _
          "tblB.TypeID as ID, " & _
          "tblAB.TypeControl as ControlID " & _
          "FROM tblB " & _
               "LEFT OUTER JOIN tblAB " & _
               "ON tblAB.TypeID = tblB.TypeID " & _
               "WHERE tblB.TypeID = " & Counter & " " & _     => Delete this one.
       ===
       and place one WHERE on ID here
       "WHERE ID = " & Counter & " " & _    => Like this one. But I am getting an error.
       ===
       "ORDER BY NewDate;"

从tblA和tblB中删除两个WHERE。 最后在ID中加一个。 并创建这个。

 SQL = "SELECT " & _
          "ADate As NewDate, " & _
          "tblA.TypeID as ID, " & _
          "tblAB.TypeControl as ControlID " & _
          "FROM tblA " & _
               "LEFT OUTER JOIN tblAB " & _
               "ON tblAB.TypeID = tblA.TypeID " & _
       "UNION ALL SELECT " & _
          "BDate As NewDate, " & _
          "tblB.TypeID as ID, " & _
          "tblAB.TypeControl as ControlID " & _
          "FROM tblB " & _
               "LEFT OUTER JOIN tblAB " & _
               "ON tblAB.TypeID = tblB.TypeID " & _
               "WHERE tblB.TypeID = " & Counter & " " & _
       "WHERE ID = " & Counter & " " & _
       "ORDER BY NewDate;"

提前致谢。

可以通过将整个查询包装在子查询中来仅检查一次 ID,然后在外部查询中检查 ID,例如:

SELECT * FROM (
    SELECT " & _
      "ADate As NewDate, " & _
      "tblA.TypeID as ID, " & _
      "tblAB.TypeControl as ControlID " & _
      "FROM tblA " & _
           "LEFT OUTER JOIN tblAB " & _
           "ON tblAB.TypeID = tblA.TypeID " & _
    "UNION ALL SELECT " & _
      "BDate As NewDate, " & _
      "tblB.TypeID as ID, " & _
      "tblAB.TypeControl as ControlID " & _
      "FROM tblB " & _
           "LEFT OUTER JOIN tblAB " & _
           "ON tblAB.TypeID = tblB.TypeID "
) WHERE ID =  " & Counter & "

但是,根据数据库引擎对此进行优化的方式,执行时间可能会更长。我建议您不要这样做,并按原样保留您的查询。

(另外,我把引号留给你,因为你的问题不应该有这些)。