MySQL - 如何计算主查询的行数,忽略子查询行?

时间:2011-07-27 15:26:53

标签: mysql sql count subquery rows

我使用以下MySQL返回帖子列表及其相应的评论。

    SELECT  *
    FROM    forum_qa
            JOIN user_profiles
              ON user_id = forum_qa_author_id
            LEFT JOIN (SELECT forum_cm_id,
                              forum_cm_author_id,
                              forum_qa_id_fk,
                              forum_cm_text,
                        FROM  forum_cm
                        JOIN  user_profiles
                          ON  user_id = forum_cm_author_id) AS c
              ON forum_qa_id = c.forum_qa_id_fk
    WHERE   forum_qa_parent_id  = $forum_qa_id

如果我跑

    $data['num_answers'] = $query->num_rows();

这允许我获取返回的行数并将数组传递给我的控制器并查看。

但这会返回 所有 行(帖子+评论)。因此,如果1个帖子有10个评论,则返回10

我怎么能让这个查询只计算不包括子查询的帖子数(即返回1)?

每封帖子都在forum_qa.forum_qa_id

中保存了唯一的ID

每条评论都在forum_cm.forum_cm_id保存了唯一的ID。

感谢您的帮助 - 如果需要,我会发布更多代码。

3 个答案:

答案 0 :(得分:2)

不是最快的,但您不限制使用GROUP BY:

SELECT  *, 
  (SELECT COUNT(*) FROM forum_qa WHERE forum_qa_parent_id  = $forum_qa_id) Cnt
    FROM    forum_qa
            JOIN user_profiles
              ON user_id = forum_qa_author_id
            LEFT JOIN (SELECT forum_cm_id,
                              forum_cm_author_id,
                              forum_qa_id_fk,
                              forum_cm_text,
                        FROM  forum_cm
                        JOIN  user_profiles
                          ON  user_id = forum_cm_author_id) AS c
              ON forum_qa_id = c.forum_qa_id_fk
    WHERE   forum_qa_parent_id  = $forum_qa_id

答案 1 :(得分:1)

您可以在结果集中运行另一个查询或添加一个列(带有独立子查询):

SELECT *
     , ( SELECT COUNT(*)
         FROM forum_qa
         WHERE forum_qa_parent_id  = $forum_qa_id
       ) AS cntPosts
FROM    forum_qa
        JOIN user_profiles
          ON user_id = forum_qa_author_id
        LEFT JOIN (SELECT forum_cm_id,
                          forum_cm_author_id,
                          forum_qa_id_fk,
                          forum_cm_text,
                    FROM  forum_cm
                    JOIN  user_profiles
                      ON  user_id = forum_cm_author_id) AS c
          ON forum_qa_id = c.forum_qa_id_fk
WHERE   forum_qa_parent_id  = $forum_qa_id

答案 2 :(得分:0)

COUNT(DISTINCT forum_qa.forum_qa_id)

COUNT(DISTINCT col_name)计算不同的帖子ID。这应该等于帖子的数量。