简体   繁体   中英

Access 2010 return most recent record from a linked table

I am tracking projects using Access with two tables:

CREATE TABLE projects
(
wonum varchar(10) NOT NULL PRIMARY KEY,
description varchar(255),
location varchar(16),
status varchar(10),
owner varchar(24),
);

CREATE TABLE comments
(
commentid AUTONUMBER NOT NULL PRIMARY KEY,
wonum varchar(10) NOT NULL,
commentdt DATETIME,
commenttext varchar(255),
FOREIGN KEY (wonum) REFERENCES projects(wonum)
);

'projects' lists each individual project and 'comments' stores comments. I'm trying to build a report that lists each individual record from 'projects' along with the most recent comment associated with that project from 'comments', along the lines of:

QueryResultSet
    project.wonum
    project.description
    project.location
    project.status
    project.owner
    comments.commenttext /*most recent comment*/

I've tried a number of different joins and subqueries from the 'net. This one seemed promising:

SELECT projects.wonum, max(comments.commentdt) AS lastdate
FROM projects INNER JOIN comments ON projects.wonum=comments.wonum
GROUP BY projects.wonum

This returns what I expect, but Access errors out when I try to include any other fields aside from projects.wonum and comments.commentdt.

One method is to use a correlated subquery to get the maximum comment for each project:

SELECT c.*
FROM projects as p INNER JOIN
     comments as c
     ON p.wonum = c.wonum
WHERE c.commentdt = (SELECT MAX(commentdt)
                     FROM comments as c2
                     WHERE c2.wonum = c.wonum
                    )
GROUP BY c.wonum

SELECT the fields you want from projects and use a correlated subquery to fetch the text from the most recent comment for each project.

SELECT
    p.wonum,
    p.description,
    p.location,
    p.status,
    p.owner,
    (
        SELECT TOP 1 c.Commenttext
        FROM comments AS c
        WHERE c.wonum = p.wonum
        ORDER BY c.commentdt DESC, c.commentid DESC
    ) AS most_recent_comment
FROM projects AS p;

I didn't know whether comments allows duplicates of commentdt for the same wonum . So I added c.commentid DESC to the ORDER BY to server as a tie-breaker for TOP 1 in case there can be duplicates. But if you have a unique constraint on the combination of wonum and commentdt , you can use just ORDER BY c.commentdt DESC

Add indexes on comments.wonum and comments.commentdt if they're not indexed already.

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