简体   繁体   中英

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". 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.

If it is logically fine, you should know.

What smells a bit are those:

  • You compare Comments with ID . Maybe it should be CommentID ?
  • The fieldname 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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