代码之家  ›  专栏  ›  技术社区  ›  HasanG Joe Dabones

另一个表上的访问计数不起作用

  •  0
  • HasanG Joe Dabones  · 技术社区  · 14 年前

    我有一个博客系统的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;
    

    但have error“您试图执行的查询未将指定的表达式'PostID'作为聚合函数的一部分。”

    3 回复  |  直到 14 年前
        1
  •  1
  •   Tim Cooper    13 年前

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

    也许你得把 JOIN

        2
  •  1
  •   Chris Diver    14 年前

    尝试

    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
    
        3
  •  0
  •   Mitch Wheat    14 年前
    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;