简体   繁体   English

如何将另一个表中的字段添加到左连接查询 MS Access

[英]How to add a field from another table to a left join query MS Access

I have a query that involves both left join and not exists statements.我有一个涉及左连接和不存在语句的查询。 Thus this query is not supported in design view.因此,设计视图中不支持此查询。 I would like to add a field "comments" from another table "Table2".我想从另一个表“Table2”中添加一个字段“评论”。 Is this possible with the query I have created?我创建的查询可以做到这一点吗? The code is as follows:代码如下:

SELECT t.NUM, t.ID, tprev.Date_ AS previous_date, tprev.Measurement AS previous_measurement
FROM Table1 AS t LEFT JOIN
     Table1 AS tprev
     ON (tprev.id = t.id) AND (tprev.Date_ < t.Date_)
WHERE not exists 
        (select 1
        from Table1 AS t1
        where 
            t1.ID = t.ID
            and t1.Date_ < t.Date_
            and t1.Date_ > tprev.Date_);

Following your example of your last comment, this query works without any complains regarding syntax:按照您上次评论的示例,此查询可以正常工作,不会对语法有任何抱怨:

SELECT t.NUM, t.ID, tprev.Date_ AS previous_date, tprev.Measurement AS previous_measurement
FROM (
     (
     Table2 AS t2
     INNER JOIN Table1 AS t
       ON (t2.Comments = t.ID)
     )
     LEFT JOIN Table1 AS tprev
       ON tprev.Date_ < t.Date_ AND tprev.id = t.id
     )
     WHERE not exists (select 1 from Table1 AS t1 where t1.ID = t.ID and t1.Date_ < t.Date_ and t1.Date_ > tprev.Date_);

The reason for the syntax error was that this parenthesis t.Date_) was too much.语法错误的原因是这个括号t.Date_)太多了。

If it is logically fine, you should know.如果逻辑上没问题,你应该知道。

What smells a bit are those:有点味道的是那些:

  • You compare Comments with ID .您将CommentsID进行比较。 Maybe it should be CommentID ?也许应该是CommentID
  • The fieldname Date_ .字段Date_ Maybe you can find a better name without having to use an underscore?也许你可以找到一个更好的名字而不必使用下划线?

Update更新

Following the comments of this answer and the new requirements, this should be what you need:根据此答案的评论和新要求,这应该是您所需要的:

SELECT
  t.NUM, t.ID, tprev.Date_ AS previous_date, tprev.Measurement AS previous_measurement, t2.Comments
FROM
  (
  Table1 AS t
  LEFT JOIN Table2 AS t2
    ON t.ID = t2.ID
  )
  LEFT JOIN Table1 AS tprev
    ON (tprev.id = t.id) AND (tprev.Date_ < t.Date_)
WHERE
  NOT EXISTS (SELECT 1 FROM Table1 AS t1 WHERE t1.ID = t.ID AND t1.Date_ < t.Date_ AND t1.Date_ > tprev.Date_)

It finally is the query of your question enhanced by another left join to add the column Comments from table2 where a corresponding comment exists.最后是另一个左连接增强了您的问题的查询,以添加来自table2的列Comments ,其中存在相应的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM