我想在一个有博客文章列表的页面上显示每个博客文章的评论数量(以及类别、日期、作者等)。如何在propel中编写以下mysql查询?

SELECT post.id, post.title, post.more_columns , COUNT(comments.post_id) AS numofcomments FROM post INNER JOIN comments ON post.id = comments.post_id GROUP BY post.id, post.title, post.more_columns

其中post是一个blog表和comments,一个post_id作为post.id外键的comments表。我似乎无法将“numofcomments”作为resultset中的列。目前,我正在使用非ORM方法(这将是我最后的选择):
$con = Propel::getConnection(PostPeer::DATABASE_NAME);

    $sql = "SELECT post.* , COUNT(comments.post_id) AS numcomments FROM post INNER JOIN comments ON post.id = comments.post_id GROUP BY post.id";
    $stmt = $con->prepare($sql);
    $stmt->execute();

    $result = PostPeer::populateObjects($stmt);
    return $result;

如何在生成的推进结果集中访问“numofcomments”?
编辑:我想知道的是如何在Propel中编写上述查询?现在我可以做的是获取带有注释表内部连接的post表,然后为每个post-id运行comments表上的doCount,这将导致一个post表查询和多个comments表查询。我希望将sql查询减少到最低限度。
谢谢:)

最佳答案

SELECT post.* , COUNT(comments.post_id) AS numcomments FROM post INNER JOIN comments ON post.id = comments.post_id GROUP BY post.id,post.secondcol,post.thirdcol;等等,只要列出post表中的所有单独列,因为您选择了post.*,就必须列出所有列,而不仅仅是post.post\u id。
交替地

SELECT post.*,sub.numcomments from post,
(select post.post_id as post_id,COUNT(comments.post_id) AS numcomments
   FROM post INNER JOIN comments ON post.id = comments.post_id GROUP BY post.id) as sub
   where post.post_id = sub.post_id;

(有一个3。还有更简单的方法,我现在忘记了……)

关于mysql - 使用Propel进行SQL查询(内部联接+计数+分组依据),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1222254/

10-16 08:51