Sql 另一个表上的访问计数不为';行不通

Sql 另一个表上的访问计数不为';行不通,sql,ms-access,join,left-join,Sql,Ms Access,Join,Left Join,我有一个博客系统的Posts表和PostComments表。我想按评论计数对帖子进行计数和排序,但我的查询不起作用: SELECT Posts.PostID, Posts.DateCreated, Posts.Title, Posts.Description, Posts.Hits, (SELECT Count(CommentID) FROM PostComments WHERE PostComments.PostID=Posts.PostID AND PostComments.IsAppro

我有一个博客系统的Posts表和PostComments表。我想按评论计数对帖子进行计数和排序,但我的查询不起作用:

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;
我还尝试:

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;
但出现错误“您试图执行的查询未将指定的表达式“PostID”作为聚合函数的一部分。”

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

我是一个完全的accessnoob,但请尝试第二个,并按非聚合列进行分组

    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]);

也许你必须在MS Access中将
JOIN
行放在大括号中。

Access要求CommentCount。啊,好吧,以前从未使用过Access,这是你在SQL Server中可以做的事情。将其更改为
COUNT([CommentID])
Right--Jet/ACE不能在ORDER BY中使用字段别名,因此必须重复精确的表达式。使用GROUP BY后发生了一件非常有趣的事情:Access将描述字段大小限制为254个字符,但字段类型实际上是memo…哎哟!许多数据库系统在分组BLOB数据方面存在问题(如2005年之前的SQL Server)。然而,254并不是太多……根据备忘录数据进行分组首先在术语上有点矛盾。在Jet 4之前,您不能对它们进行分组,而在Jet 4中,它会截断它们。这可以通过在Left()中使用返回的适当长度包装备忘录来避免(如果您已将自己退回到一个角落,并被迫对备忘录字段进行分组),以确保不会截断。
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;