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.