如何在同一查询中获取返回行数和数据的count()

时间:2011-12-19 18:29:13

标签: mysql sql

我有这个问题:

select
    problem_comments.user_id ,
    problem_comment_id ,
    problem_id ,
    first_name  ,
    count(problem_comment_id) num
from problem_comments
left join users on problem_comments.user_id = users.user_id
where problem_id = 222
group by problem_comments.comment

它是列出问题的表的基本连接,以及列出该问题的注释的另一个表。

我要对count(problem_comment_id)进行的操作是查看问题中有多少条评论,以便显示该计数。当前查询的问题是它返回3行,因为此问题有3条注释。但在“num”列中,它总是列出1。

如何继续获取相同的问题和评论数据,还能获得有多少评论总数?

谢谢!

2 个答案:

答案 0 :(得分:2)

我看到了标记,因此......执行查询后,您可以使用num_rows函数。

Here is some information if you are using mysqli.

And for PDO.

如果您使用的是mysql扩展程序(如果是,请羞辱您!),you can use mysql_num_rows()

答案 1 :(得分:1)

也许这对你有用

select
    problem_comments.user_id ,
    problem_comment_id ,
    problem_id ,
    first_name  ,
    commentCount AS num
from problem_comments
left join users on problem_comments.user_id = users.user_id
left join
(select problem_id as comment_count_problem_id, COUNT(problem_comment_id) as commentCount
 from problem_comments
 group by problem_comments.problem_id) t ON t.comment_count_problem_id = problem_id
where problem_id = 222