得到所有评论,包括对一篇文章的投票

时间:2014-03-30 11:55:36

标签: php mysql sql

我在mysql中有以下三个表格。

  

postid | post_content =>的帖子

     

commentid |发布| comment_content =>的评论

     

commentvoteid |评论|选民=>的 comment_votes

我想获取comments的所有counting its votespost

  

commentid | comment_content | comment_votes =>的 my_result

我尝试了以下查询但未获得所需的结果。

SELECT commentid,comment_content,count_comments.total AS comment_votes
FROM comments
INNER JOIN(SELECT COUNT(*) AS total FROM comment_votes WHERE comment=comments.commentid) AS count_comments
WHERE post={$postId}

是否可以按我的意愿获取结果?我怎么能这样做?

3 个答案:

答案 0 :(得分:3)

您可以使用GROUP BY来实现您的目标:

SELECT commentid,comment_content,COUNT(*) AS total
FROM comments
INNER JOIN comment_votes ON (comment_votes.comment=comments.commentid)
WHERE post={$postId}
GROUP BY commentid;

答案 1 :(得分:2)

您正在尝试的方法使用相关子查询。您可以这样做,但相关子查询需要进入select子句:

SELECT c.commentid, c.comment_content,
       (SELECT COUNT(*) FROM comment_votes cv WHERE cv.comment = c.commentid
       ) AS comment_votes
FROM comments c
WHERE post={$postId};

通常情况下,我更喜欢group by方法,但有时在MySQL中这可能会更快。

答案 2 :(得分:0)

也许是这样的:

select a.commentid, a.comment_content, count(b.*) as total from (
select commentid, comment_content from comments where post={$postId}) a
join comment_votes b on b.comment = a.commentid
group by a.commentid, a.comment_content;