开发者

Access count on another table doesn't work

I have a Posts table and PostComments table of a blog system. I want to count and sort the posts by comment count but my query won't work.:

SELECT Posts.PostID, Posts.DateCreated, Posts.Title, Posts.Description,
Posts.Hits, (SELECT Count(CommentID) FROM PostComments WHERE 
PostComments.PostID=Posts.PostID AND PostComments.IsApproved=True) AS
CommentCount FROM Posts ORDER BY Posts.PostID DESC;

I also tried:

SELECT Posts.PostID, Posts.DateCreated, Posts.Title, Posts.Description,
Posts.Hits, Count([CommentID]) AS CommentCount FROM Posts INNER JOIN PostComments
ON Posts.PostID = PostComments.PostID;

But have error "You tried to execute a query that does not include specified expression 'PostID' as a part of开发者_JS百科 an aggregate function."


I'm a complete Access noob, but try the second one with a grouping by the non-aggregated columns.

    SELECT 
       Posts.PostID
       ,Posts.DateCreated
       ,Posts.Title
       ,Posts.Description
       ,Posts.Hits
       ,Count([CommentID]) AS CommentCount 
    FROM Posts 
       INNER JOIN PostComments ON Posts.PostID = PostComments.PostID
    GROUP BY
       Posts.PostID
       ,Posts.DateCreated
       ,Posts.Title
       ,Posts.Description
       ,Posts.Hits
   ORDER BY
      Count([CommentID]);

Maybe you have to put the JOIN row into braces in MS-Access.


Try

SELECT Posts.PostID, Posts.DateCreated, Posts.Title, Posts.Description,
Posts.Hits, Count([CommentID]) AS CommentCount FROM Posts INNER JOIN PostComments
ON Posts.PostID = PostComments.PostID
GROUP BY Posts.PostID, Posts.DateCreated, Posts.Title, Posts.Description, Posts.Hits
ORDER BY Count([CommentID]) DESC


SELECT 
    Posts.PostID, 
    Posts.DateCreated, 
    Posts.Title, 
    Posts.Description, 
    Posts.Hits, 
    dr.CommentCount 
FROM Posts p
INNER JOIN 
    (SELECT PostID, Count(CommentID) as CommentCount FROM PostComments WHERE  
        PostComments.IsApproved=True GROUP BY PostId) dr ON dr.PostID = p.PostID
ORDER BY dr.CommentCount DESC;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜