2011-12-19 24 views
0

我有這個疑問:如何從他們那裏得到返回的行和數據的數量的計數()在同一個查詢

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.

我該如何不斷收回相同的問題和評論數據,同時也得到了多少條評論?

謝謝!

回答

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 
相關問題