使用Union和Left的SQL

时间:2018-04-13 10:30:59

标签: sql ms-access criteria

是否可以在[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;"

提前谢谢。

1 个答案:

答案 0 :(得分:1)

只能通过将整个查询包装在子查询中来检查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 & "

但是,根据数据库引擎如何优化它,可能需要更长时间才能执行。我建议您不要这样做,并按原样保留查询。

(另外,我把引号弄得乱七八糟,因为你的问题不管怎么说都没有。)