finding records in a table where there is at least one record in a linked table with a date field of no longer than 3 moths from now()
We have a project database in MSACCESS with the following tables: table PROJECTS with of course an ID and project details. table COMMENTS with an ID, a DATE and a comment text field.
COMMENTS is linked to PROJECTS with a one-many relation. (a project can have multip开发者_如何学Pythonle comments)
What I want is a query that selects all projects with at least one comment with a date that is less than 3 months old.
I tried an inner join and got the filter right, but I thought that with the distinctrow or distinct I could filter out the doubles, but msaccess won't accept the syntax.
It's a simple task that in any programming environment would be easy to do, but I just can't get it into a single query...
[update]: I have one little additional question: Only the records with at least one comment show up and we want new projects (with no comments yet) to show up too. I tried adding an
"OR count(SELECT projectid FROM comments WHERE (( ( comments.commentdate ) BETWEEN Dateadd("m", -3, DATE()) AND DATE()))) =0
Since you seems to want distinct Projects but not the associated comment data there are several of ways to accomplish this.
LEFT Join Distinct
SELECT DISTINCT projects.*
FROM projects
LEFT JOIN comments
ON projects.id = comments.projectid
WHERE (( ( comments.commentdate ) BETWEEN Dateadd("m", -3, DATE()) AND DATE() )
) or comments.projectid is null
LEFT Join With Group by
SELECT projects.id,
projects.fielda,
[....]
FROM projects
LEFT JOIN comments
ON projects.id = comments.projectid
WHERE (( ( comments.commentdate ) BETWEEN Dateadd("m", -3, DATE()) AND DATE() )
) or comments.projectid is null
GROUP BY
projects.id,
projects.fielda,
[....]
IN Clause
SELECT *
FROM projects
WHERE id IN (SELECT projectid
FROM comments
WHERE (( ( comments.commentdate ) BETWEEN
Dateadd("m", -3, DATE()) AND DATE()
)))
Exists Clause
SELECT *
FROM projects
WHERE EXISTS (SELECT *
FROM comments
WHERE ( comments.commentdate ) BETWEEN
Dateadd("m", -3, DATE()) AND DATE()
AND ( projects.id = comments.projectid ))
OR NOT EXISTS (SELECT *
FROM comments
WHERE projects.id = comments.projectid)
INNER JOIN to an INLINE View With a UNION to a LEFT JOIN
SELECT *
FROM projects
INNER JOIN (SELECT DISTINCT projectid
FROM comments
WHERE (( ( comments.commentdate ) BETWEEN
Dateadd("m", -3, DATE()) AND DATE()
))) comment
ON projects.id = comment.projectid
UNION ALL
SELECT *
FROM projects
LEFT JOIN comments
ON projects.id = comment.projectid
WHERE
comment.projectid is null
精彩评论